bash关于$IFS的说明:

  • The IFS is a special shell variable.
  • You can change the value of IFS as per your requirments.
  • The Internal Field Separator (IFS) that is used for word splitting after expansion and to split lines into words with the read builtin command.
  • The default value is ****. You can print it with the following command:
cat -etv <<<"$IFS"
  • IFS variable is commonly used with read command, parameter expansions and command substitution.

$IFS是shell的字符分隔符,默认是空格、tab、换行符. $IFS变量通常用于read命令(可以用作不同变量的分割符), $IFS变量还可以用于字符串分割并储存到数组变量

比如打印nginx日志不同访问码的请求数(有点多余,在此只是展示下$IFS及数组遍历)

#!/bin/bash
code_info=`awk '{print $8}' access.log|sort|count -c`
arr=($code_info)
num=${#arr[@]}
for i in $(seq 0 $[num/2])
do
  echo response_code: ${arr[$[i*2+1]] number: ${arr[$[i*2]]}
done

再比如如下的字符串切割

#!/bin/bash
a='1|2|3|4'
OLD_IFS="$IFS"
IFS="|"
arr=($a)
IFS="$OLD_IFS"
for s in ${arr[@]}
do
    echo "$s" 
done
⤧  Next post HTTP: 413 Request Entity Too Large ⤧  Previous post .bashrc与.bash_profile区别