Tilde not expanded when quoting on the right hand side of a Bash variable assignment [duplicate]

泪湿孤枕 提交于 2019-12-24 18:43:51

问题


I have made a directory ~/test_myDir

I then run the following bash script:

x="myDir"

dirName="~/test_$x"

cd $dirName
echo "hey" > test.txt

I get the following error:

test.sh: line 5: cd: ~/test_myDir: No such file or directory

I then remove the quotes from the second assignment:

x="myDir"

dirName=~/test_$x

cd $dirName
echo "hey" > test.txt

The script runs without error.

What is going on here? I ran into this issue in a larger, more complicated script, and I narrowed it down to my use of quotes in a variable assignment that contained another variable.

Still, from the error message, it looks like the full path is being expanded correctly in the "cd" call.


回答1:


Quotation marks prevent expansion of ~. Replace ~ with $HOME or use dirName=~/"test_$x".

From the manual's explanation of tilde expansion:

Each variable assignment is checked for unquoted tilde-prefixes immediately following a : or the first =. In these cases, tilde expansion is also performed.



来源:https://stackoverflow.com/questions/49846360/tilde-not-expanded-when-quoting-on-the-right-hand-side-of-a-bash-variable-assign

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