Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suggest answer to user input in bash scripting

Here is an example:

#!/bin/bash
echo -e "Enter IP address: \c"
read
echo $REPLY

But I want to make it easier for the user to answer. I'd like to offer an answer to the user. It should look something like this:

Enter your IP: 192.168.0.4

And the user can just press Enter and agree with 192.168.0.4, or can delete some characters (for example delete "4" with one backspace and type 3 instead).

How to make such an input? It is possible in bash?

like image 975
Larry Cinnabar Avatar asked Dec 18 '10 20:12

Larry Cinnabar


People also ask

Which command allows for getting user input in a script?

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 ask yes or no in bash?

In that case, we can simply wrap our yes/no prompt in a while loop. #!/bin/bash while true; do read -p "Do you want to proceed? (yes/no) " yn case $yn in yes ) echo ok, we will proceed; break;; no ) echo exiting...; exit;; * ) echo invalid response;; esac done echo doing stuff...


3 Answers

bash's read has readline support (Edit: Jonathan Leffler suggests to put the prompt into read as well)

#!/bin/bash read -p "Enter IP address: " -e -i 192.168.0.4 IP echo $IP 
like image 76
Martin v. Löwis Avatar answered Sep 28 '22 04:09

Martin v. Löwis


The way I would do this is to suggest the default in the prompt in brackets and then use the default value parameter expansion to set IP to 192.168.0.4 if they just pressed enter, otherwise it will have the value they entered.

#!/bin/bash
default=192.168.0.4
read -p "Enter IP address [$default]: " IP
IP=${IP:-$default}
echo "IP is $IP"

Output

$ ./defip.sh
Enter IP address [192.168.0.4]:
IP is 192.168.0.4

$ ./defip.sh
Enter IP address [192.168.0.4]: 192.168.1.1
IP is 192.168.1.1
like image 21
SiegeX Avatar answered Sep 28 '22 02:09

SiegeX


The classic way to do most of what you want is:

default="192.168.0.4"
echo -e "Enter IP address ($default): \c"
read reply
[ -z "$reply" ] && reply=$default
echo "Using: $reply"

This doesn't give the editing option.

like image 45
Jonathan Leffler Avatar answered Sep 28 '22 02:09

Jonathan Leffler