Echoing a tilde to a file without expanding it in Bash

萝らか妹 提交于 2019-12-01 16:41:56

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"
David W.

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.

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