Setting IFS for a single statement

我只是一个虾纸丫 提交于 2019-12-04 08:54:52

I was going to comment on this when I saw you use it, but it didn't occur to me until just now what the problem was. The line

IFS=: d=($myvar)

doesn't temporarily set IFS; it simply sets two variables in the current shell. (Simple commands can be prefixed with local environment settings, but an assignment statement itself is not a simple command.)

When you write

echo $IFS

IFS expands to :, but because : is the first character of IFS, it is removed during word splitting. Using

echo "$IFS"

would show that IFS is still set to :.

IFS behaves fine with read on the same line:

myvar="a:b:c"
IFS=: read -ra d <<< "$myvar"
printf "%s\n" "${d[@]}"
a
b
c

Check value of IFS:

declare -p IFS
-bash: declare: IFS: not found

so clearly IFS has not been tampered in current shell.

Now check original input:

echo $myvar
a:b:c

or:

echo "$myvar"
a:b:c

In bash, you can set set a variable that is valid for a single statement only if that statement is not itself a variable assignment. For example:

$ foo=one bar=two
$ echo $foo
one

To make the second assignment part of a statement, you need ... some other statement. As you've noticed, eval works. In addition, read should work:

$ foo="one:two:three"
$ IFS=: read -r -a bar <<< "$foo"
$ declare -p bar
declare -a bar='([0]="one" [1]="two" [2]="three")'
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!