If we would like to ask the user for input then we use a command called read
in our bash scripts. This command takes the input and will save it into a variable.
Here are two slightly different versions of the same shell script. This first version prompts the user for input only once, and then dies if the user doesn’t give a correct Y/N answer:
# (1) prompt user, and read command line argument read -p "Run the cron script now? " answer # (2) handle the command line argument we were given while true do case $answer in [yY]* ) /usr/bin/wget -O - -q -t 1 http://www.example.com/cron.php echo "Okay, just ran the cron script." break;; [nN]* ) exit;; * ) echo "Dude, just enter Y or N, please."; break ;; esac done
This second version stays in a loop until the user supplies a Y/N answer:
while true do # (1) prompt user, and read command line argument read -p "Run the cron script now? " answer # (2) handle the input we were given case $answer in [yY]* ) /usr/bin/wget -O - -q -t 1 http://www.example.com/cron.php echo "Okay, just ran the cron script." break;; [nN]* ) exit;; * ) echo "Dude, just enter Y or N, please.";; esac done
This Linux Bash ‘read’ function is nice, because it does both things, prompting the user for input, and then reading the input. We prefer the second approach, but thought we’d share both of them here. They are subtly different, but note the extra break in the first script.