Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to just input 'y' without having to press ENTER?

Tags:

bash

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?

like image 528
boudiccas Avatar asked Jan 19 '14 14:01

boudiccas


People also ask

How do you ask for input in bash?

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.

How do you prompt a shell script?

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.


1 Answers

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).

like image 167
Gordon Davisson Avatar answered Sep 22 '22 17:09

Gordon Davisson