我尝试使用名为file sth.txt
的cat
文件。当我写时
cat "file sth.txt"
它非常有效。
当我将file sth.txt
保存到变量file
中并执行时
cat "$file"
系统写入
cat: file: No such file or directory
cat: sth.txt: No such file or directory
我想用变量cat
文件,并且其中有多个文件名。对于没有空格的文件名,它是有效的。有人能给我一些建议吗?
您必须像这样分配变量:
file="file sth.txt"
或:
file="$1"
您确定您的变量包含正确的数据吗?您也应该使用""
或''
或使用
:来转义变量中的路径
rr-@luna:~$ echo test > "file sth.txt"
rr-@luna:~$ var=file sth.txt
rr-@luna:~$ cat "$var"
test
rr-@luna:~$ var="file sth.txt"
rr-@luna:~$ cat "$var"
test
版本=GNU bash, version 4.3.33(1)-release (i686-pc-cygwin)
试试这个,这就是Mac OS X的终端处理此类情况的方式。
cat /path/to/file sth.txt
你可以用你的脚本做同样的事情
sh script.sh /path/to/file sth.txt
使用数组:
# Put all your filenames in an array
arr=("file sth.txt") # Quotes necessary
arr+=("$1") # Quotes necessary if $1 contains whitespaces
arr+=("foo.txt")
# Expand each element of the array as a separate argument to cat
cat "${arr[@]}" # Quotes necessary
如果你发现自己依赖于分词(即,你在命令行上扩展的变量被它们所包含的空格分割成多个参数),那么通常最好使用数组。