Search code examples
bashif-statementnestedshnested-if

How to fix this bash script?


I have this script here:

killall -q $1
#turns out system already has a method for this, yey
#-q because we already have a error handling
returned=$?
#does this so that it doesn't read the success state of the ifs
if [ $returned = 0 ]
then 
    printf "Process kill attempt returned "
    echo $returned
    echo "Process killed sucessfully."
    #yey we did it
else
    #oh noes it failed
    printf "Process kill attempt returned "
    echo $returned
    echo "Process kill attempt failed."
    printf "Most likely cause of failure: "
    if [ $returned = 1 ]
    then
        echo "process does not exist or is not running"
    elif [ $returned = 2 ]
        echo "process is system task; insufficient permissions"
    else
        echo "unknown failure " $returned "; no known fail in database has this value"
    fi
fi

When looking at it, I see no problem, yet when run, I get this error.

nathan@HAL-LINUX:~$ xscreensaver
nathan@HAL-LINUX:~$ killproc xscreensaver
/usr/local/bin/killproc: line 23: syntax error near unexpected token `else'
/usr/local/bin/killproc: line 23: ` else'
nathan@HAL-LINUX:~$ 

My original script omitted the nested if, by just straight up telling you it failed with error 3 or 1 or 2.

Should I go back? Or is there a way to fix this?


Solution

  • You forgot the then after your elif:

    if [ $returned = 1 ]
        then
            echo "process does not exist or is not running"
        elif [ $returned = 2 ]
        then
            echo "process is system task; insufficient permissions"
        else
            echo "unknown failure " $returned "; no known fail in database has this value"
        fi