0

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'
saikiran
  • 71
  • 2
  • 8

1 Answers1

1

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'
  • This fixes one bug but not all of them -- `==` should be `=` for portability to minimal POSIX implementations of `[`. See https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html – Charles Duffy Jan 22 '22 at 14:59
  • May be you telling the truth but since he just need to compare 'Y' only ... – Putra Budiman Jan 22 '22 at 22:48
  • If this code is run on a shell that doesn't support `==`, it will say false even when `$i` _is_ `Y`. I don't know how "need to just compare 'Y' only" makes the objections above no longer valid. See also https://stackoverflow.com/a/20449556/14122 – Charles Duffy Jan 22 '22 at 22:53