“~/Desktop/test.txt:没有这样的文件或目录”
我写了这个脚本:
#!/bin/bash
file="~/Desktop/test.txt"
echo "TESTING" > $file
该脚本不起作用;它给了我这个错误:
./tester.sh: line 4: ~/Desktop/test.txt: No such file or directory
我做错了什么?
I've written this script:
#!/bin/bash
file="~/Desktop/test.txt"
echo "TESTING" > $file
The script doesn't work; it gives me this error:
./tester.sh: line 4: ~/Desktop/test.txt: No such file or directory
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将
~
替换为$HOME
。仅当波浪号未被引用时才会发生波浪号扩展。请参阅信息“(bash)波浪线扩展”
。您也可以在不引用它的情况下执行
file=~/Desktop
,但是如果您用其中包含字段分隔符的内容替换其中的一部分,那么它就会中断。无论如何,引用变量的值可能是一个好习惯。引用变量file=~/"Desktop"
也可以,但我认为这相当难看。如果可能的话,更喜欢
$HOME
的另一个原因是:波形符扩展仅发生在单词的开头。因此,只有当command
本身进行波形符扩展时,command --option=~/foo
才会起作用,这会因命令而异,而command --option="$ HOME/foo"
将始终有效。Try replacing
~
with$HOME
. Tilde expansion only happens when the tilde is unquoted. Seeinfo "(bash) Tilde Expansion"
.You could also do
file=~/Desktop
without quoting it, but if you ever replace part of this with something with a field separator in it, then it will break. Quoting the values of variables is probably a good thing to get into the habit of anyway. Quoting variablefile=~/"Desktop"
will also work but I think that is rather ugly.Another reason to prefer
$HOME
, when possible: tilde expansion only happens at the beginnings of words. Socommand --option=~/foo
will only work ifcommand
does tilde expansion itself, which will vary by command, whilecommand --option="$HOME/foo"
will always work.仅供参考,您还可以使用
eval
:eval
将命令作为参数,它会导致 shell 执行 波浪号扩展。FYI, you can also use
eval
:The
eval
takes the command as an argument and it causes the shell to do the Tilde expansion.