首页 > 解决方案 > 在 bash 中运行 while 循环时二进制运算符预期错误

问题描述

TL:博士

检查给定的 PID 是否正在运行,如果是,则终止该进程。

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

为此,我收到一个错误:

第 8 行:[:-p: 期望二元运算符

我知道有几个类似的问题,我已经尝试过他们的解决方案,但它似乎不起作用。

标签: linuxbash

解决方案


while正如@kvantour 所提到的,循环在逻辑上是不正确的。这是脚本。请注意,如果它无法终止进程,它会通知您,以便您调查根本原因。该脚本将 PID 作为其第一个参数(例如$./kill-pid.sh 1234)请注意,这适用于 bash 版本。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

推荐阅读