设置为IFS一个语句 [英] Setting IFS for a single statement

查看:140
本文介绍了设置为IFS一个语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 GNU bash的版本42年3月4日(1)-release 我做的一些测试的回答一个问题。我们的想法是分割 - 分隔字符串,以及它的每个元素到数组

On my GNU bash, version 4.3.42(1)-release I am doing some tests to answer a question. The idea is to split a :-separated string and and each of its elements into an array.

对于这一点,我尝试设置 IFS 在命令的范围,从而使分裂是自动的, IFS 保持不变:

For this, I try to set the IFS to : in the scope of the command, so that the split is automatic and IFS remains untouched:

$ myvar="a:b:c"
$ IFS=: d=($myvar)
$ printf "%s\n" ${d[@]}
a
b
c

和显然 IFS 仍然是相同的:


$ echo $IFS
                      # empty

借助 BASH参考说:

如果IFS没有设置,参数用空格分隔。如果是IFS
  空,则该参数被接合而不介入隔膜

If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

不过,我注意到 IFS 是种坏了,让回声$ myvar的收益 ABC 而不是 A:b:C

However, then I notice that the IFS is kind of broken, so that echo $myvar returns a b c instead of a:b:c.

取消设置值解决它:

$ unset IFS
$ echo $myvar
a:b:c

不过,我想:是什么原因造成的?是不是 IFS =:命令更改 IFS 只需在命令的范围正在执行

But I wonder: what is causing this? Isn't IFS=: command changing IFS just in the scope of the command being executed?

设置为IFS一个语句看到的,这确实是工作的:

I see in Setting IFS for a single statement that this indeed works:

$ IFS=: eval 'd=($myvar)'
$ echo $myvar
a:b:c

但我不明白为什么它和 IFS =:D =($ myvar的)

推荐答案

我本来打算在这个时候,我看见你用它来发表评论,但它并没有想到我直到刚才的问题是什么。行

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)

暂时不设置 IFS ;它只是设置在当前shell两个变量。 (简单的命令可以与当地的环境设置pfixed $ P $,但赋值语句本身就不是一个简单的命令。)

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.)

当你写

echo $IFS

IFS 扩展到,但因为 IFS 的第一个字符,这词的拆分过程中被删除。使用

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

echo "$IFS"

将显示 IFS 仍设置为

这篇关于设置为IFS一个语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆