2

Being relatively new to anything other than bash scripting, I have created a script to

  • check if a process is running
  • output PID's to the shell
  • if not prompt user input and start etc/etc.

I've moved onto positional parameters and can't see where I'm going wrong:

if [ "$1" == "" ]; then
    proc_finder
elif [ $1 != "" ];then
    case $1 in
        -p | --process ) 
        shift
        z=$(ps aux |grep $1 |grep -v grep  > /dev/null)
        if [ ! -z "$z" ]; then
            echo "YES"
        else
            echo "NO"
        fi
    ;;
    * )
        echo "Usage -p (process)"
    esac
fi

This always seems to return yes even when putting in -p test for example. I know im doing something fundamentally wrong, looking at the verbose output the grep -v grep is being done last hence I believe it always returnes an exit state of 0.

1
  • 1
    ps aux | grep $1 | grep -v grep should be simplified to ps -C $1, if possible - at least Linux ps is able to do so. Commented Feb 19, 2012 at 10:30

1 Answer 1

1

Shouldn't that be if [ $? -eq 0 ]?

EDIT 1

You can try this:

z=`ps aux | grep $1 | grep -v grep > /dev/null`
if [ ! -z "$z" ]; then
    echo "YES"
else
    echo "NO"
fi

If $z is not empty (-z: test for zero-length string) this implies the process was found with the ps command.

EDIT 2

The ps ... grep ... grep is being redirect to /dev/null. That means z will contain nothing. remove the redirection and z should have some output.

z=`ps aux | grep $1 | grep -v grep`

EDIT 3

Alternatively, you can just do this:

ps aux | grep $1 | grep -v grep > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "YES"
else
    echo "NO"
fi

In this case, you are not saving the grep output. That's good if you don't really need it.

Sign up to request clarification or add additional context in comments.

5 Comments

Why do you have a pipe | after the grep -v grep call? And what's the $z meant to be doing all by itself? That will always return 0
+ case $1 in + shift + echo test test ++ ps aux ++ grep test ++ grep -v grep + z= + '[' '!' -z == '' ']' + echo YES YES
Backticks are deprecated. The $(...) construct, used by @user1217286 is much better: easy nestable, better readable.
@userunknown Thank you for pointing that out. Although I'm not sure how it would help readability, but I can appreciate the $(...) construct as far as nesting goes.
Backticks get sometimes overseen, and some fonts make it hard to distinguish them from apostrophes.

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.