bash有空格的文件名

时间:2023-06-13 08:12:32

http://www.keakon.net/2011/10/20/bash%E4%B8%8B%E5%A4%84%E7%90%86%E5%8C%85%E5%90%AB%E7%A9%BA%E6%A0%BC%E7%9A%84%E6%96%87%E4%BB%B6%E5%90%8D

例如,我在当前文件夹下建立3个文件名包含空格的文件:

keakons-MacBook-Pro:test keakon$ touch "test 1"
keakons-MacBook-Pro:test keakon$ touch "test 2"
keakons-MacBook-Pro:test keakon$ touch "test 3"
keakons-MacBook-Pro:test keakon$ ls
test 1 test 2 test 3

然后for循环输出文件名:

keakons-MacBook-Pro:test keakon$ for file in `ls`;
> do echo $file;
> done
test
1
test
2
test
3

可以看到,文件名被分开了。

复制操作也不行:

keakons-MacBook-Pro:test keakon$ mkdir ../bak
keakons-MacBook-Pro:test keakon$ for file in `ls`; do cp "$file" ../bak; done
cp: bak is a directory (not copied).
cp: test: No such file or directory
cp: 1: No such file or directory
cp: test: No such file or directory
cp: 2: No such file or directory
cp: test: No such file or directory
cp: 3: No such file or directory

要解决这个问题,当然就要从单词分隔符着手。而bash中使用的是$IFS(Internal Field Separator)这个变量,内容为" \n\t":

keakons-MacBook-Pro:test keakon$ echo $IFS

keakons-MacBook-Pro:test keakon$ echo "$IFS" | od -t x1
0000000 20 09 0a 0a
0000004
keakons-MacBook-Pro:test keakon$ echo "" | od -t x1
0000000 0a
0000001

然后把它改成"\n\b",记得修改前先保存一下:

keakons-MacBook-Pro:test keakon$ SAVEIFS=$IFS
keakons-MacBook-Pro:test keakon$ IFS=$(echo -en "\n\b")

现在再执行上述命令就正常了:

keakons-MacBook-Pro:test keakon$ for file in `ls`; do echo $file; done
test 1
test 2
test 3
keakons-MacBook-Pro:test keakon$ for file in `ls`; do cp "$file" ../bak; done
keakons-MacBook-Pro:test keakon$ ls ../bak
test 1 test 2 test 3

最后,别忘了恢复$IFS:

keakons-MacBook-Pro:test keakon$ IFS=$SAVEIFS
keakons-MacBook-Pro:test keakon$ echo "$IFS" | od -t x1
0000000 20 09 0a 0a
0000004
keakons-MacBook-Pro:test keakon$ IFS=$(echo -en " \n\t")
keakons-MacBook-Pro:test keakon$ echo "$IFS" | od -t x1
0000000 20 0a 09 0a
0000004