There was a problem working with files today, and the for loop is problematic when the file name contains spaces.
For example, I create 3 files in the current folder that contain spaces:
Copy Code code 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 for loop output filename:
Copy Code code 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 filename is separated.
The copy operation does not work either:
Copy Code code 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, it is of course necessary to start with the word separator. And bash uses the $ifs (Internal Field Separator) variable, which reads "\n\t":
Copy Code code as follows:
Keakons-macbook-pro:test keakon$ Echo $IFS
Keakons-macbook-pro:test keakon$ echo "$IFS" | OD-T x1
0000000 0a 0a
0000004
Keakons-macbook-pro:test keakon$ echo "" | OD-T x1
0000000 0a
0000001
Then change it to "\n\b", remember to save before the change:
Copy Code code as follows:
Keakons-macbook-pro:test keakon$ saveifs= $IFS
Keakons-macbook-pro:test keakon$ ifs=$ (echo-en "\n\b")
It is normal to execute the above command now:
Copy Code code 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 the $ifs:
Copy Code code as follows:
keakons-macbook-pro:test keakon$ ifs= $SAVEIFS
Keakons-macbook-pro:test keakon$ echo "$IFS" | OD-T x1
0000000 20 09 0a 0a & nbsp;
0000004
keakons-macbook-pro:test keakon$ ifs=$ (echo-en "\n\t")
Keakons-macbook-pro:te St keakon$ echo "$IFS" | OD-T x1
0000000 20 0a 09 0a & nbsp;
0000004