vimal
vimal

Reputation: 75

What is wrong in this Shell script?

I keep getting unary operator expected. It seems PRC is not being assigned the value.

PRC=`ps -ef | grep test | wc -l`
if [ ${PRC} -eq 1 ]
then
    echo "Congrats"

Upvotes: 0

Views: 80

Answers (2)

Gary_W
Gary_W

Reputation: 10360

Don't forget your closing "fi":

PRC=`ps -ef | grep test| wc -l`
if [ "${PRC}" -eq 1 ]
then
    echo "Congrats"
fi

You didn't mention what shell, but this works in bash.

Save a process by using the -c (count) option to grep:

PRC=`ps -ef | grep -c test`

Be advised your pipeline includes in the count the grep command itself, so as you mentioned in your comment above your count is most likely misleading as it is only counting itself. Instead, use this:

 PRC=`ps -ef | grep -c [t]est`

This will match commands with "test" in them but not the grep command itself. This is because this is using a regular expression that matches a word starting with a "t". Your command starts with a square bracket so it won't match itself. Resist doing a "grep test | grep -v grep" which is sloppy and just unnecessarily uses a process.

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247162

Note that ps -ef | grep test will usually include the grep process in the output, which you probably don't want. A "clever trick" to avoid this is to match for the string "test" with a regular expression that is not the simple string "test":

$ ps -ef | grep test
jackman  27787 24572  0 09:53 pts/2    00:00:00 grep --color=auto test
$ ps -ef | grep test | wc -l
1

versus

$ ps -ef | grep '[t]est'
(no output)
$ ps -ef | grep '[t]est' | wc -l
0

I do this often enough that I wrote this bash function psg (for "ps grep"):

psg () { 
    local -a patterns=()
    (( $# == 0 )) && set -- $USER     # no arguments? vanity search
    for arg do
        patterns+=("-e" "[${arg:0:1}]${arg:1}")
    done
    ps -ef | grep "${patterns[@]}"
}

You could also just use

pgrep -f test

Upvotes: 2

Related Questions