【问题标题】:Concatenate inputs in string while in loop在循环中连接字符串中的输入
【发布时间】:2017-08-13 12:53:38
【问题描述】:

我有一个源变量,它基本上是一串以逗号分隔的元素:

SOURCES="a b c d e"

我希望用户为每个源输入一个目的地,因此我想将此输入存储到一个类似于上面但包含目的地的字符串中。如果我想分配 a=1、b=2... 等,我会这样:

echo $DESTINATIONS >>> "1 2 3 4 5"

为了做到以上几点,我这样做:

SOURCES="a b c d e"
DESTINATIONS=""

for src in $SOURCES
do
    echo Input destination to associate to the source $src:
    read dest
    DESTINATIONS=$DESTINATIONS $dest
done

但是,如果我在 $DESTINATIONS 上执行 echo,我会发现它是空的。 此外,在每个循环中,我的 shell 都会告诉我:

-bash: = **myInput**: command not found

知道我哪里做错了吗?

【问题讨论】:

  • SOURCES 中没有逗号分隔?只是空格分隔?

标签: string bash sh string-concatenation


【解决方案1】:
SOURCES="a b c d e"
DESTINATIONS=""

for src in $SOURCES
do
    echo Input destination to associate to the source $src:
    read dest
    DESTINATIONS+=" ${dest}"
done
echo $DESTINATIONS

为我工作。

【讨论】:

  • 非常感谢。 “dutiona” :)
【解决方案2】:

您的代码最明显的问题是这一行:

DESTINATIONS=$DESTINATIONS $dest

相反,上面一行应该写成:

DESTINATIONS="$DESTINATIONS $dest"

问题:您正在执行 $dest 并传递 DESTINATIONS=$DESTINATIONS 的环境。这有望解释您看到的错误消息。

我用我建议的引号尝试了你的代码,它工作正常。

【讨论】:

    【解决方案3】:

    您应该使用数组,而不是分隔字符串。

    sources=(a b c d e)
    
    for src in "${sources[@]}"
    do
        read -p "Input destination to associate to the source $src" dest
        destinations+=( "$dest" )
    done
    
    printf '%s\n' "${destinations[@]}"
    

    【讨论】:

      【解决方案4】:

      问:怎么了?
      A:在需要的地方不要使用引号。

      如果您使用未加引号的空格,shell 将使用它来分割行。

      使用时:

      DESTINATIONS=$DESTINATIONS $dest
      

      shell 将变量 $dest 理解为要执行的命令,这就是您收到错误的原因:

      -bash: = **myInput**: command not found
      

      要解决问题,只需引用空格即可。
      有几种方法可以做到这一点:

      DESTINATIONS=$DESTINATIONS" "$dest
      DESTINATIONS=$DESTINATIONS' '$dest
      DESTINATIONS="$DESTINATIONS"' '"$dest"
      DESTINATIONS="$DESTINATIONS $dest"
      

      最后一个选项可能是最简单的,也是整体上最好的。
      您也可以使用这种语法(从 bash 3.1-alpha1 开始):

          DESTINATIONS+=" $dest"
      

      另外,请!引用您的其他扩展:

      echo "$DESTINATIONS"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-27
        • 2015-12-16
        • 2013-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-20
        • 2017-01-20
        相关资源
        最近更新 更多