Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script that asks user to continue with a y/n

Tags:

bash

shell

I have a shell script that I want to ask the user if they want to continue. If they type 'n' and press enter the script will exit.

If they press 'y' and enter it will continue to run. I have this at the top of my script but it continues regardless of what I type.

What am I doing wrong ?

goon=
while [ -z $goon ]
do
    echo -n 'Do you want to continue? '
    read goon
    if [[ $goon = 'n' ]]
    then
        break
    fi
    goon=
done
like image 751
32423hjh32423 Avatar asked Feb 14 '26 02:02

32423hjh32423


2 Answers

Use an infinity loop and case/esac like this:

while true
do
    read -r -p 'Do you want to continue? ' choice
    case "$choice" in
      n|N) break;;
      y|Y) echo 'Do your stuff here';;
      *) echo 'Response not valid';;
    esac
done
like image 84
ghostdog74 Avatar answered Feb 16 '26 16:02

ghostdog74


The 'break' statement will exit you out of your while loop.

If you want to exit the script you want to use 'exit'.

like image 22
Jumipo Avatar answered Feb 16 '26 17:02

Jumipo