在“ for循环”中使用IFS

杰克·陈
lis="a:b:c:d:"

IFS=:

如果我运行以下代码,

for i in "a:b:c:d:";
do 
    echo the output is $i
done

我得到:

the output is a b c d

如果我用$ lis代替“ a:b:c:d:”:

for i in $lis;
do 
    echo the output is $i
done

我有预期的输出:

the output is a
the output is b
the output is c
the output is d

我想知道哪里出了问题,$ lis与“ a:b:c:d”基本相同

塞尔吉(Sergiy Kolodyazhnyy)

最大的区别在于执行单词拆分的位置。双引号可确保将文字字符串或带引号的变量(例如)"$lis"视为单项

for i in "a:b:c:d:";
do 
    echo the output is $i
done

因此,在此循环中,双引号"a:b:c:d:"是单个项目,因此为什么只看到一行输出

the output is a b c d

for i in $lis;
do 
    echo the output is $i
done

此处$lis未加引号,因此外壳程序将根据IFS您设置执行单词拆分Shell将看到为for循环提供了4个项目。因此,为什么看到四行输出。

如果使用双引号"$lis"变量,则不会执行单词拆分,因此您应该看到与第一种情况相同的输出-仅一行。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章