itsh
itsh

Reputation: 1123

Simple case statement is failing in shell script

I had written a very simple case statement which is failing. I double checked the syntax but could not find what went wrong. Can somebody please let me know?

#!/bin/bash

opt_type=0


function opt_type
{
        echo "Opt Porvisioning tool starting..."

        echo -e "1. ABC \n2. DEF \n3. HIJ \n"
        read opt_input

        case $opt_input in
        1|abc|ABC)
                opt_type=1;

        2|def|DEF)    
                opt_type=2;

        3|hij|HIJ)    
                opt_type=3;

        4|exit|Exit) echo "Exiting ..."

        *) echo "Please enter a valid entry. Exiting!!"

        esac
}

echo $opt_type


./opt_type.sh: line 16: syntax error near unexpected token `)'
./opt_type.sh: line 16: `       2|def|DEF)
-bash-3.2$ 

I don't see any such symbol (`) then why is it complaining?

Upvotes: 0

Views: 1365

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185861

You must close each cases by ;; not ; =)

So :

#!/bin/bash

opt_type=0


function opt_type
{
        echo "Opt Porvisioning tool starting..."

        echo -e "1. ABC \n2. DEF \n3. HIJ \n"
        read opt_input

        case $opt_input in
        1|abc|ABC)
                opt_type=1
        ;;
        2|def|DEF)    
                opt_type=2
        ;;
        3|hij|HIJ)    
                opt_type=3
        ;;
        4|exit|Exit) echo "Exiting ..."
        ;;
        *) echo "Please enter a valid entry. Exiting!!"
        ;;
        esac
}

echo $opt_type

Upvotes: 1

Stephen Ostermiller
Stephen Ostermiller

Reputation: 25585

In Bash you need two semicolons after each case in your case statement. I also took the case statement out of the function, since the function was never called. The following works as expected

#!/bin/bash
opt_type=0
echo "Opt Porvisioning tool starting..."
echo -e "1. ABC \n2. DEF \n3. HIJ \n"
read opt_input
case $opt_input in
    1|abc|ABC) opt_type=1;;
    2|def|DEF) opt_type=2;;
    3|hij|HIJ) opt_type=3;;
    4|exit|Exit) echo "Exiting ...";;
    *) echo "Please enter a valid entry. Exiting!!";;
esac
echo $opt_type

Upvotes: 0

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13900

You should double semicolons:

case $opt_input in
    1|abc|ABC)
        opt_type=1;;
    2|def|DEF)    
        opt_type=2;;
    3|hij|HIJ)    
        opt_type=3;;
    4|exit|Exit)
        echo "Exiting ...";;
    *)
        echo "Please enter a valid entry. Exiting!!";;
esac

Upvotes: 1

Related Questions