【问题标题】:Linux bash string split using IFS on single quoteLinux bash 字符串拆分在单引号上使用 IFS
【发布时间】:2014-03-03 11:53:57
【问题描述】:

在 Linux bash 中有很多关于 IFS 字符串拆分和单引号转义的已回答问题,但我发现没有人加入这两个主题。偶然发现这个问题,我得到了一个奇怪的(对我来说)行为,代码如下所示:

(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]}

发生的情况是数组的 echo 元素实际上包含我需要的子字符串(因此导致我认为 \' IFS 是正确的) 而 for 循环返回按空格分割的字符串。

有人能帮我理解为什么同一个数组(或者我认为同一个数组)会这样吗?

【问题讨论】:

    标签: linux bash quotes string-split ifs


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      相关资源
      最近更新 更多