[英]"~/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?我究竟做错了什么?
Try replacing ~
with $HOME
.尝试用
$HOME
替换~
。 Tilde expansion only happens when the tilde is unquoted.波浪号扩展仅在波浪号未被引用时发生。 See
info "(bash) Tilde Expansion"
.请参阅
info "(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.您也可以在不引用它的情况下执行
file=~/Desktop
,但是如果您将其中的一部分替换为带有字段分隔符的内容,那么它就会中断。 Quoting the values of variables is probably a good thing to get into the habit of anyway.无论如何,引用变量的值可能是养成习惯的一件好事。 Quoting variable
file=~/"Desktop"
will also work but I think that is rather ugly.引用变量
file=~/"Desktop"
也可以,但我认为这很丑陋。
Another reason to prefer $HOME
, when possible: tilde expansion only happens at the beginnings of words.在可能的情况下,更喜欢
$HOME
另一个原因是:波浪号扩展只发生在单词的开头。 So command --option=~/foo
will only work if command
does tilde expansion itself, which will vary by command, while command --option="$HOME/foo"
will always work.所以
command --option=~/foo
只有在command
本身进行波浪号扩展时才有效,这会因命令而异,而command --option="$HOME/foo"
将始终有效。
FYI, you can also use eval
:仅供参考,您也可以使用
eval
:
eval "echo "TESTING" > $file"
The eval
takes the command as an argument and it causes the shell to do the Tilde expansion . eval
将命令作为参数,它会导致 shell 进行波浪号扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.