2

我的印象是设置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=','read解析dd,ee,ff为三个字段?

4

1 回答 1

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'

编辑:当变量没有被引用时,扩展会导致分

shell 会扫描双引号内未出现的参数扩展、命令替换和算术扩展的结果以进行分词。

于 2014-01-06T11:26:53.713 回答