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$ 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