【问题标题】:Print current iteration in while loop在while循环中打印当前迭代
【发布时间】:2020-04-26 02:19:51
【问题描述】:

我的脚本中有以下行,${snap[@]} 数组包含我的 ssh 服务器列表。

      while IFS= read -r con; do
    ssh foo@"$con" /bin/bash <<- EOF
      echo "Current server is $con"
EOF
      done <<< "${snap[@]}"

我想在 ssh 成功运行时打印数组的当前迭代值,$con 应该打印当前的 ssh 服务器 --> example@server。我该怎么做?

【问题讨论】:

    标签: bash loops while-loop heredoc


    【解决方案1】:

    如果snap 中的元素是您要连接的主机,只需使用for 循环:

    for con in "${snap[@]}"; do
      # connect to "$con"
    done
    

    "${snap[@]}" 扩展为数组snap 中安全引用的元素列表,适用于for

    如果你真的想使用while,那么你可以这样做:

    i=0
    while [ $i -lt ${#snap[@]} ]; do # while i is less than the length of the array
      # connect to "${snap[i]}"
      i=$(( i + 1 ))                 # increment i
    done
    

    但正如您所见,它比基于for 的方法更尴尬。

    【讨论】:

    • 我知道for 循环可以做到这一点,但我正在寻找while 解决方案,谢谢。
    • 我强烈推荐使用for 的方法,但我还是添加了一个使用while 的选项。
    • 在明确需要for 循环时,为什么还要使用while 循环?
    • 你不需要使用set;您可以只使用while 循环来生成可用于索引snapi 的递增值。
    • @chepner 是的,你是对的,我用更简单的选项替换了我的示例,谢谢。
    【解决方案2】:

    像这样:

    while IFS= read -r con; do
        ssh "foo@$con" /bin/bash <<EOF
            echo "Current server is $con"
    EOF
    done < <(printf '%s\n' "${snap[@]}")
    #    ____
    #      ^
    #      |
    # bash process substitution < <( )
    

    或者简单地说:

    for server in "${snap[@]}"; do
        ssh "foo@$con" /bin/bash <<EOF
            echo "Current server is $con"
    EOF
    done
    

    【讨论】:

    • 使用printfwhile read 循环的组合来迭代数组的内容似乎过于复杂。
    • @TomFenech 是的,添加了for loop 版本
    猜你喜欢
    • 2016-12-21
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2020-09-21
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多