Bash 脚本在Continue 语句后中断

Bash 脚本在Continue 语句后中断

在这里,我尝试远程 ssh 到多个服务器,并检查这些服务器上是否有任何进程正在运行,并等待该进程完成。

while read ip name
do
  process=alive
  while [[ "$process" == "alive" ]]
  do
    process=dead
    (if [ 1 -eq "$(echo "$(ssh ubuntu@$ip "top -b -n2 -d 0.5|grep Cpu|awk '{print \$2+\$4}'|tail -n1") > 1" | bc)" ];then
      echo "Process is running on $ip"
      process=alive
      sleep 10
      continue 
    else
      echo "Process is not running on $ip"
      echo "I run some other commands here"
    fi) &
  done
done < ips
wait `jobs -p`

代码在“继续”语句后被破坏。

这是输出

+ read ip name
+ process=alive
+ [[ alive == \a\l\i\v\e ]]
+ process=dead
+ [[ dead == \a\l\i\v\e ]]
+ read ip name
+ process=alive
+ [[ alive == \a\l\i\v\e ]]
+ process=dead
+ [[ dead == \a\l\i\v\e ]]
+ read ip name
++ jobs -p
++ bc
+ wait 31090 31091
+++ ssh [email protected] 'top -b -n2 -d 0.5|grep Cpu|awk '\''{print $2+$4}'\''|tail -n1'
++ bc
+++ ssh [email protected] 'top -b -n2 -d 0.5|grep Cpu|awk '\''{print $2+$4}'\''|tail -n1'
++ echo '20.7 > 1'
+ '[' 1 -eq 1 ']'
+ echo 'Process is running on 249.X.X.X'
Process is running on 249.X.X.X
+ process=alive
+ sleep 10
++ echo '14.6 > 1'
+ '[' 1 -eq 1 ']'
+ echo 'Process is running on 256.X.X.X'
Process is running on 256.X.X.X
+ process=alive
+ sleep 10
+ continue
+ continue

答案1

替换sshssh -n停止从 stdin(文件 ips)读取。


看:man ssh

答案2

不过,使用ssh -n重定向/dev/null到标准输入ssh应该可以解决眼前的问题。如果没有-nssh将从文件中读取ips。但是您在代码中还做了其他不必要的事情。

更正后的代码:

while read ip name; do
    (
    while true; do
        if ssh -n "ubuntu@$ip" top -b -n2 -d 0.5 | awk '/Cpu/ && n++ { exit($2+$4 > 1) }'
            printf 'Process is running on %s\n' "$ip"
            sleep 10
        else
            printf 'Process is not running on %s\n' "$ip"
            echo 'I run some other commands here'
            break
       fi
    done
    ) &
done <ips

wait

我已经简化了你的代码

  • top不尝试在远程主机上运行更多内容,
  • 直接使用退出值awkwith if,
  • 用于break打破(现在)无限循环,
  • 在后台作业中运行该循环,不仅仅是语句if,并且
  • 使用wait不带任何参数来等待所有后台进程。

if另一种完全不需要该语句的变体:

while read ip name; do
    (
    while ssh -n "ubuntu@$ip" top -b -n2 -d 0.5 | awk '/Cpu/ && n++ { exit($2+$4 > 1) }'
    do
        printf 'Process is running on %s\n' "$ip"
        sleep 10
    done
    printf 'Process is not running on %s\n' "$ip"
    echo 'I run some other commands here'
    ) &
done <ips

wait

相关内容