2014-03-03 54 views
0

在Linux bash中有很多关于IFS字符串拆分和单引号转义的回答问题,但是我没有发现任何加入这两个主题的答案。在蹒跚问题我得到像一个在这里下面的代码的奇怪(我)行为:在单引号中使用IFS的Linux bash字符串拆分

(bash脚本块)

theString="a string with some 'single' quotes in it" 

old_IFS=$IFS 
IFS=\' 
read -a stringTokens <<< "$theString" 
IFS=$old_IFS 

for token in ${stringTokens[@]} 
do 
    echo $token 
done 

# let's say $i holds the piece of string between quotes 
echo ${stringTokens[$i]} 

会发生什么事是,呼应 -ed元该数组实际上包含我需要的子串(因此导致我认为IFS是正确的),而for循环返回空格上的字符串split。

有人可以帮助我理解为什么相同的数组(或我脑子里看起来像是同一个数组)的行为如何?

回答

1

当你这样做:

for token in ${stringTokens[@]} 

循环实际上就变成了:

for token in a string with some single quotes in it 

for循环不解析数组元素明智的,但它解析分隔字符串的整个输出空间。

而是尝试:

for token in "${stringTokens[@]}"; 
do 
    echo "$token" 
done 

这将等同于:

for token in "in a string with some " "single" " quotes in it" 

输出在我的电脑:

a string with some 
single 
quotes in it 

检查了这一点为更多的bash陷阱: http://mywiki.wooledge.org/BashPitfalls