1. Definition
The environment variable IFS, called the internal field separator, defines a series of characters that the bash shell uses as field separators. By default, the bash shell treats the following characters as field separators:
- space
- Tabs
- newline
2. Issues related to IFS
If the bash shell sees any of these characters in the data, it assumes that this indicates the start of a new data field in the list. When dealing with data containing spaces, it can be very troublesome.
Suppose there is a file status.txt with the following contents:
Alaska Arizona Arkansas Colorado Connecticut Delaware Florida Georgia New York New Hampshire North Carolina
There are spaces in the data in the last three lines of the file. When using the for loop to read each line, since the space is the default field separator, the bash shell considers that a new field is read when encountering a space, and the following problems occur.
The shell script is as follows:
1 #!/bin/ bash 2 # Read every line in the file 3 4 file = " status.txt " 5 for line in $( cat ${ file }) 6 do 7 echo " Visit beautiful $line " 8 done
The results are as follows:
As you can see, the for loop treats each space-separated word as a separate value, rather than each row as a separate value. To solve this problem, you can temporarily change the value of the environment variable IFS in the shell script to limit the characters used as field separators by the bash shell. Modify the script as follows:
1 #!/bin/ bash 2 # Read every line in the file 3 4 file = " status.txt " 5 IFS=$ ' \n ' 6 for line in $( cat ${ file }) 7 do 8 echo " Visit beautiful $line " 9 done
Running the script again yields the following results:
When dealing with scripts with a large amount of code, it may be necessary to modify the value of IFS in one place, and then ignore this modification and continue to use the default value of IFS in other parts of the script. A safe practice to refer to is to save the original IFS value before changing the IFS and restore it later, as follows:
1 IFS.OLD= $IFS 2 IFS= $'\n' 3 #Use the new IFS in the next code 4 #codes 5 #Restore the original value of IFS after use 6 IFS=$IFS.OLD