itsh
itsh

Reputation: 1123

if else statement is failing in shell script

I have a very simple shell script which is failing at if-else. And I am not able to understand what is wrong. I checked my syntax and indentation.

echo_usr()
{
    read -p "Do you want to preserve $EIP_HOME/conf and $EIP_HOME/installer/.datastore? [Y/N] " usr_in

    kill_java()

    if [ "$usr_in" == "y*" ] || [ "$usr_in" == "Y*" ]; then
        preserve_conf()
    else
        if [ "$usr_in" == "n*" ] || [ "$usr_in" == "N*" ]; then
            reset_home_eip()
        else
            echo "Invalid input"
        fi
    fi

    reset_db()
}

It is giving me the following error: syntax error near unexpected token `else'

Upvotes: 2

Views: 551

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263627

To call a function with no arguments, just use the name of the function. Empty parentheses are not necessary, and in fact are a syntax error. (Or, more precisely, it's part of the syntax for a function definition, and if you try to use it as a function call you'll get a syntax error message later -- if you're lucky.)

The idea is that a call to a shell function looks and acts like an invocation of an external program.

For example, change:

preserve_conf()

to

preserve_conf

(Using elif rather than else followed by if is a good idea, but it's not the cause of the problem you're seeing.)

There's another problem that you won't see until you get past the syntax error (thanks to Sam for pointing it out in a comment). This:

if [ "$usr_in" == "y*" ] || [ "$usr_in" == "Y*" ]; then

isn't going to work correctly; the == operator used by the [ / test built-in doesn't do wildcard matching. If you're using bash, you can use [[ rather than [, and you can also combine the y and Y cases into a single pattern:

if [[ "$usr_in" == [yY]* ]] ; then
    ...
elif [[ "$usr_in" == [nN]* ]] ; then
    ...
fi

If you don't have a shell that supports that syntax, a case statement might be your next best bet -- in fact that's probably even cleaner than the if version:

case "$usr_in" in
    [yY]*)
        ...
        ;;
    [nN]*)
        ...
        ;;
    *)
        ...
        ;;
esac

Upvotes: 6

Related Questions