0

TL:DR

Check if a given PID is running, if yes kill the process.

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

I am aware there are several similar questions, I already tried their solutions but it doesn't seem to work.

4
  • I don't get your code. What does that while loop supposed to do 4 times? Commented Feb 5, 2020 at 6:51
  • You are placing a command in the Test-Statement. This does not work the way you think it should work. while [[ "$count" -le 3 ]] && ps -p $pid > /dev/null; do ... done Commented Feb 5, 2020 at 6:52
  • The kill command should repeat, just in case the process wasn't killed the first time. But if for some reason, the process does not die, I do not want the program to be stuck in an infinite loop, hence a exit condition Commented Feb 5, 2020 at 6:52
  • OK, the reason behind a process not being killed might be complex. I will re-write your bash script as an answer, which will let end-user know if the process cannot be killed. Commented Feb 5, 2020 at 6:55

1 Answer 1

1

The while loop is logically incorrect, as @kvantour mentioned. 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 (e.g. $./kill-pid.sh 1234) Note that this works for bash ver. 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
Sign up to request clarification or add additional context in comments.

2 Comments

How about if I want to attempt to kill the process one more time before returning the control to the user?
you can use a for loop, or, if you want to get a very quick but dirty answer from the code above, you can just add the line kill -9 $1 after the line echo "$output". If the process is not killed, it will attempt one more time to kill the process and then exits, it will also echo the output in the console as well. OK, I will just add this to the code in commented format, remove the hashtag in your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.