我的印象是设置IFS
会更改read
在将一行文字分成字段时使用的分隔符,但显然我遗漏了一些内容:
# OK: 'read' sees 3 items separated by spaces
$ (IFS=' '; x="aa bb cc"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'aa bb cc'
'aa' 'bb' 'cc'
# OK: 'read' sees a single item after IFS is changed
$ (IFS=','; x="aa bb cc"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'aa bb cc'
'aa bb cc' '' ''
# Why doesn't 'read' see 3 items?
$ (IFS=','; x="dd,ee,ff"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'dd,ee,ff'
'dd ee ff' '' ''
# OK: 'read' sees a single item when IFS is restored.
$ (IFS=' '; x="dd,ee,ff"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'dd,ee,ff'
'dd,ee,ff' '' ''
# OK: 'read' again sees 3 items separated by spaces.
$ (IFS=' '; x="gg hh ii"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'gg hh ii'
'gg' 'hh' 'ii'
为什么IFS=','
不{/ 1}}将read
解析为dd,ee,ff
三个字段?
答案 0 :(得分:6)
# Why doesn't 'read' see 3 items?
$ (IFS=','; x="dd,ee,ff"; echo "'$x'"; read a b c <<< $x;\
echo "'$a' '$b' '$c'")
'dd,ee,ff'
'dd ee ff' '' ''
因为你没有引用变量。
$ ( IFS=','; x="dd,ee,ff"; echo "'$x'"; read a b c <<< "$x";\
echo "'$a' '$b' '$c'")
'dd,ee,ff'
'dd' 'ee' 'ff'
编辑:当未引用变量时,扩展会导致Word Splitting:
shell扫描参数扩展命令的结果 替换和未发生的算术扩展 用于分词的双引号。