简体   繁体   English

在bash中运行while循环时二元运算符预期错误

[英]Binary operator expected error while running a while loop in bash

TL:DR翻译:博士

Check if a given PID is running, if yes kill the process.检查给定的 PID 是否正在运行,如果是,则终止该进程。

count=0
  while [[ "$count" -le 3 && ps -p $pid > /dev/null ]];
  do
   kill -9 $pid
   count=$(( $count + 1 )):
  done

To this I am getting an error as:为此,我收到一个错误:

line 8: [: -p: binary operator expected第 8 行:[: -p:预期的二元运算符

I am aware there are several similar questions, I already tried their solutions but it doesn't seem to work.我知道有几个类似的问题,我已经尝试过他们的解决方案,但似乎不起作用。

The while loop is logically incorrect, as @kvantour mentioned.正如@kvantour 提到的, while循环在逻辑上是不正确的。 Here is the script.这是脚本。 Note that it will let you know if it could not kill the process, so you can investigate the root cause.请注意,如果它无法终止进程,它会通知您,以便您调查根本原因。 The script gets PID as its first argument (eg $./kill-pid.sh 1234 ) Note that this works for bash ver.该脚本将 PID 作为其第一个参数(例如$./kill-pid.sh 1234 )请注意,这适用于 bash 版本。 4.1+: 4.1+:

#!/usr/bin/env bash

if ps -p $1 > /dev/null

then
  output=$(kill -9 $1 2>&1)
    if [ $? -ne 0 ]
    then
      echo "Process $1 cannot be killed. Reason:"
      echo "$output"
# This line is added per OP request, to try to re-run the kill command if it failed for the first time.
#      kill -9 $1
    fi
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM