Creating interactive “yes” or “no” SHELL script

scripting

During programming sometimes we need ¬†make script more interactive. There is little example how we can do such interactive script which is asking simple question about continuing and we will quit program by pressing “c” char. I hope this example is understandable for everyone.

while true; do
    read -p 'do you want to continue "y" or "n": ' yn

    case $yn in

        [Yy]* ) echo 'this program continue '; break;;

        [Nn]* ) exit;;

        * ) echo 'Please answer yes or no: ';;

    esac

done

while true; do
    read -p 'press "c" to quit this program: ' c

    case $c in

        [Cc]* ) exit;;

        * ) echo 'for quit this program press "c": ' ;;

    esac

done

The output of this program will be as follow.

#
# ./ynscript
do you want to continue "y" or "n": y
this program continue
press "c" to end this program: c
#
# ./ynscript
do you want to continue "y" or "n": n
#
# ./ynscript
do you want to continue "y" or "n": g
Please answer yes or no.
do you want to continue "y" or "n": n
#
#

Leave a Reply