SoFunction
Updated on 2025-03-10

Processing filename instances containing spaces in the shell

I encountered a problem when processing files today. When the file name contains spaces, the for loop has problems.

For example, I create 3 files with file names containing spaces under the current folder:

Copy the codeThe code is as follows:
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

Then the for loop output file name:
Copy the codeThe code is as follows:
keakons-MacBook-Pro:test keakon$ for file in `ls`;
> do echo $file;
> done
test
1
test
2
test
3

As you can see, the file names are separated.

The copy operation is not possible:

Copy the codeThe code is as follows:
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

To solve this problem, of course, we must start with the word separator. The variable $IFS (Internal Field Separator) is used in bash, and the content is "\n\t":

Copy the codeThe code is as follows:
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

Then change it to "\n\b", remember to save it before modifying:

Copy the codeThe code is as follows:
keakons-MacBook-Pro:test keakon$ SAVEIFS=$IFS
keakons-MacBook-Pro:test keakon$ IFS=$(echo -en "\n\b")

Now it will be normal to execute the above command:

Copy the codeThe code is as follows:
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

Finally, don't forget to restore $IFS:

Copy the codeThe code is as follows:
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