Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"[: too many arguments" appears occasionally with pidof

Tags:

shell

 cplane_pid=`pidof hnb_gw.exe`
    if [ -z $cplane_pid ]
    then
        STATUS=`failure`
        echo "Cplane hnbgw running     $STATUS"
    else
        STATUS=`success`
        echo "Cplane hnbgw running     $STATUS"
    fi      
    echo
like image 458
Deepak Avatar asked Jun 18 '13 09:06

Deepak


2 Answers

If there are multiple instances of hnb_gw.exe, pidof will return multiple pids. The -z of [ expects only one pid. One solution might be to use the -s switch of pidof to return only one pid.

like image 100
urzeit Avatar answered Oct 20 '22 05:10

urzeit


You need to Use More Quotes™:

if [ -z "$cplane_pid" ]

Adding set -x before and set +x after the command shows you what it results in. For example:

$ cplane_pid="1 2 3"
$ set -x
$ [ -z $cplane_pid ]
+ '[' -z 1 2 3 ']'
bash: [: too many arguments

In other words, each of the whitespace-separated values in the variable was used as a single parameter. Since -z requires exactly one parameter, this results in a syntax error.

Rather than saving this as a variable, you can simply do

if ! pidof hnb_gw.exe > /dev/null

If the process doesn't exist, it will return 1 ("false").

like image 4
l0b0 Avatar answered Oct 20 '22 05:10

l0b0