如何使 bash 脚本使用带空格的文件名?
How to make bash script take file names with spaces?
I have a bash script like this:
myfiles=("file\ with\ spaces.csv")
for file_name in "${myfiles[@]}"
do
echo "removing first line of file $file_name"
echo "first line is `head -1 $file_name`"
echo "\n"
done
but it does not recognize the spaces for some reason, even though I enclosed it in double quotes ""
:
head: cannot open ‘file\’ for reading: No such file or directory
How do I fix this?
反引号内需要双引号。外层不够用。
echo "first line is `head -1 "$file_name"`"
另外,不要在文件名中加入反斜杠,因为它已经被引用了。引号或反斜杠,但不能同时使用。
myfiles=("file with spaces.csv")
myfiles=(file\ with\ spaces.csv)
展开:
- Quoting 需要一点时间来适应 Bash。作为一个简单的规则,对没有特殊字符的静态字符串使用单引号,对具有变量的字符串使用双引号,对具有特殊字符的字符串使用
$''
引号。
- 每个 command substitution.
中都有一个单独的引用上下文
$()
是建立命令替换的更清晰的方法,因为它可以更容易地嵌套。
因此,您通常会写 myfiles=('file with spaces.csv')
和 echo "first line is $(head -1 "$file_name")"
。
I have a bash script like this:
myfiles=("file\ with\ spaces.csv")
for file_name in "${myfiles[@]}"
do
echo "removing first line of file $file_name"
echo "first line is `head -1 $file_name`"
echo "\n"
done
but it does not recognize the spaces for some reason, even though I enclosed it in double quotes ""
:
head: cannot open ‘file\’ for reading: No such file or directory
How do I fix this?
反引号内需要双引号。外层不够用。
echo "first line is `head -1 "$file_name"`"
另外,不要在文件名中加入反斜杠,因为它已经被引用了。引号或反斜杠,但不能同时使用。
myfiles=("file with spaces.csv")
myfiles=(file\ with\ spaces.csv)
展开
- Quoting 需要一点时间来适应 Bash。作为一个简单的规则,对没有特殊字符的静态字符串使用单引号,对具有变量的字符串使用双引号,对具有特殊字符的字符串使用
$''
引号。 - 每个 command substitution. 中都有一个单独的引用上下文
$()
是建立命令替换的更清晰的方法,因为它可以更容易地嵌套。
因此,您通常会写 myfiles=('file with spaces.csv')
和 echo "first line is $(head -1 "$file_name")"
。