The full name of IFS is Interal Field Separator, the "inner Zone delimiter", which is also a built-in environment variable that stores the default text delimiter, which by default is a whitespace (space character), tab (tab), and New lines ( NewLine). Let's look at one of the following simple examples:?
12345678 |
#!/bin/sh msg= "welcome to www groad net" for item in $msg do echo "Item: $item" done |
Run output:
# sh temp.sh item:welcome item:to item:www item:groad item:net
The above uses a for loop to iterate through all the items in the variable MSG. Each word stored in the MSG variable is separated by a space, and for can take the words out in turn, relying on the IFS variable as the delimiter. If you change the MSG variable to the CSV (comma separaed values comma separated value) format, you cannot parse the individual words by default IFS values, such as:
sh temp.sh item:welcome,to,www,groad,net
This way, the entire string is taken as an item.
If you still want to get each word individually, you need to modify the value of the IFS variable, such as:?
1234567891011121314 |
#!/bin/sh data= "welcome,to,www,groad,net" IFSBAK=$IFS #备份原来的值 IFS=, for item in $data do echo Item: $item done IFS=$IFSBAK #还原 |
Run output:
# sh tmp.sh item:welcome item:to item:www item:groad item:net
The magical character of the ################# Shell: variable ifs
the magic of word separation in the shell: variable Ifsshell treats each $IFS character as a delimiter and splits the results of other extensions based on these characters. If the IFS is not set, or if its value is exactly "'", then any sequence of IFS characters is sent to the split word. Self-writing a simple script: #!/bin/Bash forIinch' cat/etc/passwd ' Doecho $idone Output result: test33:x:506: -::/home/test33:/bin/bashtest44:x:507: +::/home/test44:/bin/bashtest55:x:508: -::/home/test55:/bin/bashtest66:x:509: -::/home/test66:/bin/Bash if/etc/passwd has the fifth column, which is the comment, which contains spaces in the comments, as follows: test33:x:506: -::/home/test33:/bin/bashtest44:x:507: +::/home/test44:/bin/bashtest55:x:508: -::/home/test55:/bin/bashtest66:x:509: -: User test1:/home/test66:/bin/what is the result of bash execution, chaos: test33:x:506: -::/home/test33:/bin/bashtest44:x:507: +::/home/test44:/bin/bashtest55:x:508: -::/home/test55:/bin/bashtest66:x:509: -: Usertest1:/home/test66:/bin/The Bash program considers spaces in comments as character separators. In order to solve this problem, the $IFS variable can be used: #!/bin/Bashifs_old=$IFS #将原IFS值保存 to recover IFS after use=$ ' \ n ' #更改IFS值为 $ ' \ n ', note that to enter as a delimiter, IFS must be: $ ' \ n ' forIinch' Cat m.txt ' DoEcho $idoneIFS=$IFS _old #恢复原IFS值再次运行, get the expected Result: test33:x:506: -::/home/test33:/bin/bashtest44:x:507: +::/home/test44:/bin/bashtest55:x:508: -::/home/test55:/bin/bashtest66:x:509: -: User Test1:/home/test66:/bin/bash
The magic of Word separation in the shell: variable ifs