bash “~/Desktop/test.txt:没有那个文件或目录”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8409024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:08:44  来源:igfitidea点击:

"~/Desktop/test.txt: No such file or directory"

bashshellunix

提问by Mason

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?

我究竟做错了什么?

回答by Michael Hoffman

Try replacing ~with $HOME. Tilde expansion only happens when the tilde is unquoted. See info "(bash) Tilde Expansion".

尝试替换~$HOME. 波浪号扩展仅在波浪号未加引号时发生。见info "(bash) Tilde Expansion"

You could also do file=~/Desktopwithout 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.

您也可以file=~/Desktop不引用它,但是如果您将其中的一部分替换为带有字段分隔符的内容,那么它就会损坏。无论如何,引用变量的值可能是养成习惯的一件好事。引用变量file=~/"Desktop"也可以,但我认为这很丑陋。

Another reason to prefer $HOME, when possible: tilde expansion only happens at the beginnings of words. So command --option=~/foowill only work if commanddoes tilde expansion itself, which will vary by command, while command --option="$HOME/foo"will always work.

$HOME在可能的情况下,更喜欢 的另一个原因是:波浪号扩展只发生在单词的开头。所以command --option=~/foo只有command在波浪号扩展本身时才有效,这将因命令而异,而command --option="$HOME/foo"将始终有效。

回答by Sanghyun Lee

FYI, you can also use eval:

仅供参考,您还可以使用eval

eval "echo "TESTING" > $file"

The evaltakes the command as an argument and it causes the shell to do the Tilde expansion.

eval作为参数取指令,它会导致壳做波浪线扩展