Echoing a tilde to a file without expanding it in Bash

僤鯓⒐⒋嵵緔 提交于 2019-12-19 17:41:44

问题


I need to write an argument to a file in a Bash script, so I'm doing something like this,

echo "Argument is: $1" >> file

The problem is that if there's a tilde (~) in the argument I don't want it expanded to the home directory. So if the user passed ~/bin as an argument to the script, it would get written as ~/bin and not /home/user/bin. How do I do this?


回答1:


I assume your program is started as:

$ your_prog ~/foo

The argument is translated before your program is even started, so there's nothing you can do to prevent it other than educating the user to quote appropriately if the expansion is not desired:

$ your_prog "~/foo"



回答2:


You can use read command to accept user-input.

read var
echo "$var"



回答3:


Charles Duffy has the correct answer. You're program is behaving exactly as expected. Try these:

$ echo The HOME directory is ~
$ echo "The HOME directory is ~"

You'll see that merely putting the tilde in quotes is preventing the expansion.

The reason, despite your quotes, that you don't see the tilde is that the shell is expanding the tilde before your program even gets it as an argument.

The shell in Unix is a very powerful creature in its own right. It handles expansion of variable and special characters like ~ and *, so your program doesn't have to.

As an old professor once told me, "This is very good except when it isn't". In this particular case "it isn't". The Unix shell is preventing you from seeing what you want.

The only way around this is to get rid of the shell. You can do that by using the read statement.



来源:https://stackoverflow.com/questions/12240940/echoing-a-tilde-to-a-file-without-expanding-it-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!