Using this portion of a bash script as an example
{
read -p "Do you want to update the tv feed? [y/n/q] " ynq
case $ynq in
[Yy]* ) rm ~/cron/beeb.txt; /usr/bin/get-iplayer --type tv>>~/cron/beeb.txt;;
[Nn]* ) echo;;
[Qq]* ) exit;;
* ) echo "Please answer yes or no. ";;
esac
}
How do I get it so that you can press y and not have to press Enter for it to be accepted please?
If we would like to ask the user for input then we use a command called read. This command takes the input and will save it into a variable.
You can use the built-in read command ; Use the -p option to prompt the user with a question. It should be noted that FILEPATH is the variable name you have chosen, and is set with the answer to the command prompt. So if you were to then run vlc "$FILEPATH" , for example, vlc would open that file.
Add -n 1
to the read
command's options. From the bash manpage:
-n nchars
read returns after reading nchars characters rather than
waiting for a complete line of input.
BTW, you should also double-quote "$ynq"
-- sometimes users will just press return, which can cause weird behavior if the variable isn't double-quoted. Also, note that read -n
is a bash extension, so make sure you're using bash (i.e. #!/bin/bash
or similar for the first line of the script), not a brand-x shell (#!/bin/sh
or similar).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With