在 while 循环中打印当前迭代
Print current iteration in while loop
我的脚本中有以下行,${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
。我该怎么做?
像这样:
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
如果 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
的方法更笨拙。
我的脚本中有以下行,${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
。我该怎么做?
像这样:
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
如果 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
的方法更笨拙。