Population Xplosive
Population Xplosive

Reputation: 617

shell - Yes no prompt not working using case

I am using bash 4.2 to create a prompt

        read -p "Want to print the output to $newname ? (y/n)" $yesno
        case "$yesno" in
           [Yy])
                   outname=$newname;;
           [Nn])
                   echo "Quitting ...";
                   exit 4;;
           *) 
                   echo "Quitting !!";
                   exit 5;;
        esac

The problem is that whether I give y or n, the output is "Quitting !!"

But if I comment the case *), the result equates outname to newname

What am I doing wrong?

Upvotes: 0

Views: 200

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133428

Could you please try following. 2 things I have fixed in OP's code.

i- We need NOT to put $ while reading value from user in variable yesno.

ii- I have changed user's entered input to small letters so no need to check both the y|Y or n|N responses here.

read -p "Want to print the output to $newname ? (y/n)" yesno
case $(tr '[:upper:]' '[:lower:]' <<< "$yesno") in
y)
   outname=$newname
   echo "In y condition here...."
   ;;
n)
   echo "Quitting ..."
   exit 4
;;
*)
   echo "Default Quitting !!";
   exit 5
   ;;
esac

When I run above code:

./script.ksh
Want to print the output to  ? (y/n)y
In y condition here....

Upvotes: 2

Ivan
Ivan

Reputation: 7253

Variable name in read have to be without $

read -p "Want to print the output to $newname ? (y/n)" yesno

Upvotes: 2

Related Questions