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?
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"
You can use read
command to accept user-input.
read var
echo "$var"
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