Search code examples
linuxshellunixvi

When user doesnt enter any choice


I need to ask user in unix shell script to enter input to proceed further in a code block. Need to display 'Hi' only when user enters Y (case sensitive) otherwise just display 'Bye'. 'Bye' should be displayed when user hits enter key on keyboard or when he wont enter any input.

Also, please note that, I need to show either of echo messages based on user input and finally reach 'Proceeding to next line of code' code as well.

I am getting below error for else condition when user hits enter key [: ==: unary operator expected

echo 'Do you want to proceed?'
read i
if [ $i == 'Y' ]
then
   echo 'Hi'
else
   echo 'Bye'
fi

echo 'Proceeding to next line of code'

Solution

  • Just add double quotes in your variable:

    echo 'Do you want to proceed?'
    read i
    if [ "$i" == 'Y' ]
    then
        echo 'Hi'
    else
        echo 'Bye'
    fi
    echo 'Proceeding to next line of code'