“~/Desktop/test.txt:没有那个文件或目录" [英] "~/Desktop/test.txt: No such file or directory"
问题描述
我写了这个脚本:
#!/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
我做错了什么?
推荐答案
尝试将 ~
替换为 $HOME
.波浪号扩展仅在波浪号未加引号时发生.请参阅信息(bash)波浪号扩展"
.
Try replacing ~
with $HOME
. Tilde expansion only happens when the tilde is unquoted. See info "(bash) Tilde Expansion"
.
您也可以在不引用它的情况下执行 file=~/Desktop
,但是如果您将其中的一部分替换为带有字段分隔符的内容,那么它就会中断.无论如何,引用变量的值可能是养成习惯的一件好事.引用变量 file=~/"Desktop"
也可以,但我认为这很丑陋.
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 variable file=~/"Desktop"
will also work but I think that is rather ugly.
在可能的情况下更喜欢 $HOME
的另一个原因:波浪号扩展只发生在单词的开头.所以 command --option=~/foo
仅在 command
本身进行波浪号扩展时才有效,这会因命令而异,而 command --option="$HOME/foo"
将始终有效.
Another reason to prefer $HOME
, when possible: tilde expansion only happens at the beginnings of words. 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.
这篇关于“~/Desktop/test.txt:没有那个文件或目录"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!