简体   繁体   English

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

[英]"~/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.

相关问题 为什么“gnome-screensaver-command -q > test.txt”不输出到文件? - Why “gnome-screensaver-command -q > test.txt” do not output to file? 尝试使用 sed 命令将此 var 包含在 test.txt 文件中以删除双引号 - Attempting to include this var in the test.txt file using sed command to remove double quotes 将文件名目录复制到.txt文件的脚本 - Script to copy directory of filenames to .txt file 遍历目录并将文件名输出到txt文件 - loop over a directory and output file names to a txt file 读取目录并将每个子目录放在txt文件的一行中 - Read directory and put each subdirectories in one line of txt file 如何在特定目录(-mmin -1)中查找特定文件(txt)? - How to find a specific file(txt) in a specific directory(-mmin -1)? Bash循环 - 为目录中的每个现有txt文件创建一个文件夹 - Bash loop - creating a folder for each existing txt file in a directory 如何使用vim打开目录下的每个.txt文件(使用Bash) - how to use vim to open every .txt file under a directory (with Bash) Grep 返回 'grep: node_list.txt: No such file or directory' 错误 - Grep returns 'grep: node_list.txt: No such file or directory' error 如何在测试的biginig中将变量字符串传递到文件txt? - How to pass a variable string to a file txt at the biginig of test?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM