A while-read Loop

I found myself in need of a way to optionally run the same line of code before a script exited.  Well… need… it’s what I wanted.  Anyway.

After some trouble sorting out some syntax issues and some confusion about how to get a while loop to depend upon some user input, I came up with this code snippet which I will do just what I wanted.

##
# by JamesIsIn

variable=y
while [ "${variable}" = "y" ]
do

   ## What you want repeated goes here.##
   ## What you want repeated goes here.##

     read -e -p "Do you want to go again? [y/n]"
     echo $REPLY
     ## variable="${REPLY,,}" ## after bash v4 ##
     ## variable="$( echo "${REPLY}" | tr '[A-Z]' '[a-z]' )" ## for Mac and bash < v4 ##
     echo $variable
     if [[ "${variable}" = y ]]; then
          echo "Ok!"
     elif [[ "${variable}" = yes ]]; then
          echo "Ok!"
     else
          echo "Damn!"
          variable=n
     fi
done

##

As you can see, the line which takes the REPLY and pushes it into variable is repeated.  This is because there is a simpler way to make the reply lower-case starting with bash v4.  I included both lines in case anyone wants to use this on older versions of bash (including on Macs which still use an archaic version of bash).  Just uncomment the line for your system.

Enjoy.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *