转自:http://smilejay.com/2011/12/bash_ifs/
在bash中IFS是内部的域分隔符,manual中对其的叙述如下:
IFS The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is ”.
如下是一些值得注意的地方。
1. IFS的默认值为:空白(包括:空格,tab, 和新行),将其ASSII码用十六进制打印出来就是:20 09 0a (见下面的shell脚本)。
2. IFS对空格的空白的处理和其他字符不一样,左右两边的纯空白会被忽略,多个连续的空白被当成一个IFS处理。
3. S*中使用IFS中的第一个字符。
4. awk中的FS(域分隔符)也和IFS有类似的用法和作用。
我写了一个shell脚本来演示IFS的用法和作用,如下:
#! /bin/bash
#author: Jay Ren
#date: 2011.12.10 echo "----------------------------------IFS test--------------------------------"
echo "default \$IFS is:(ASSII in hexadecimal value)"
echo -n "$IFS" | xxd -g 1 | awk -F":" '{print $2}' | awk -F" " '{print $1, $2, $3}'
echo "by default, IFS should be a SPACE, a HORIZONTAL TAB, or a LINC FEED." function output_args_one_per_line()
{
arg_list=$*
echo "\$*='$*'"
for arg in $arg_list
do
echo "[$arg]"
done
} echo "--------------------------------------------------------------------------"
echo "set IFS=' ' #dealing with SPACE in IFS is different with other chars."
echo "var=' a b c '"
IFS=' '
var=" a b c "
output_args_one_per_line $var echo "--------------------------------------------------------------------------"
echo "set IFS=':'"
echo "var='::a:b::c:::'"
IFS=':'
var="::a:b::c:::"
output_args_one_per_line $var echo "--------------------------------------------------------------------------"
echo "set IFS='+:-;' #but \$* just use 1st char in IFS as the separator."
echo "var='::a:b::c:::'"
IFS='+:-;'
var="::a:b::c:::"
output_args_one_per_line $var echo "--------------------------------------------------------------------------"
echo "set IFS='-+:;' #but \$* just use 1st char in IFS as the separator."
echo "var='::a:b::c:::'"
IFS='-+:;'
var="::a:b::c:::"
output_args_one_per_line $var echo "--------------------------The END of IFS test-----------------------------"
结果
master@jay-linux:~/workspace/mygit/shell/sh2011$ ./IFS-test.sh
----------------------------------IFS test--------------------------------
default $IFS is:(ASSII in hexadecimal value)
20 09 0a
by default, IFS should be a SPACE, a HORIZONTAL TAB, or a LINC FEED.
--------------------------------------------------------------------------
set IFS=' ' #dealing with SPACE in IFS is different with other chars.
var=' a b c '
$*='a b c'
[a]
[b]
[c]
--------------------------------------------------------------------------
set IFS=':'
var='::a:b::c:::'
$*='::a:b::c::'
[]
[]
[a]
[b]
[]
[c]
[]
--------------------------------------------------------------------------
set IFS='+:-;' #but $* just use 1st char in IFS as the separator.
var='::a:b::c:::'
$*='++a+b++c++'
[]
[]
[a]
[b]
[]
[c]
[]
--------------------------------------------------------------------------
set IFS='-+:;' #but $* just use 1st char in IFS as the separator.
var='::a:b::c:::'
$*='--a-b--c--'
[]
[]
[a]
[b]
[]
[c]
[]
--------------------------The END of IFS test-----------------------------