Penguin
Penguin

Reputation: 21

Command executes fine in terminal, not in a bash script

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?

Upvotes: 0

Views: 123

Answers (3)

glenn jackman
glenn jackman

Reputation: 247162

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

Upvotes: 3

Penguin
Penguin

Reputation: 21

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

Upvotes: 0

choupit0
choupit0

Reputation: 49

I suggest to use square brackets also:

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

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

Upvotes: 0

Related Questions