0

I'm trying:

#!/bin/bash
if $(ps -C "bm_d21_debug")
then
    kill $(ps -C "bm_d21_debug" -o pid=)
    echo "exists"
fi

It returns: "PID: command not found"

Not sure what I'm doing wrong?

4
  • 2
    I suggest: if ps -C "bm_d21_debug" Commented Feb 23, 2019 at 20:13
  • 1
    You'll want to read the pkill man page. It'll make your life easier. Commented Feb 23, 2019 at 20:43
  • It's just weird that if I copy and paste kill $(ps -C "bm_d21_debug" -o pid=) it works fine. but if I copy and paste this whole block, it dies on that line: kill $(ps -C "bm_d21_debug" -o pid= Commented Feb 23, 2019 at 20:46
  • 1
    Shellcheck automatically detects this issue. You can have your editor point them out on the fly. Commented Feb 23, 2019 at 23:37

3 Answers 3

3

Consider this line:

if $(ps -C "bm_d21_debug")

You execute the ps command in a command substitution, which returns the command output. The if command then tries to run that output as a command.

The first word of the ps output is PID, which if will handle as the command name. Thus, the "command not found" error.

You just want

if ps -C "bm_d21_debug" >/dev/null; then
    echo running
else
    echo NOT running
fi
Sign up to request clarification or add additional context in comments.

1 Comment

This was my issue. Thanks!
0

I suggest to use square brackets also:

if [[ $(ps -C "bm_d21_debug") ]]

But this command will always return "yes" ($? = 0)

1 Comment

Square brackets scare me, but I fixed it by changing to this code: stackoverflow.com/a/54846069/11107107 Thanks!
0

Fixed by changing to

if ps aux | grep ./bm_d21_debug | grep -v grep >/dev/null;then
    pid=$(ps aux | grep ./bm_d21_debug | grep -v grep | awk '{print $2}')
    kill $pid
    echo $pid
fi

Comments

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.