How to prompt user for input in shell script?

2020-02-28 14:37发布

问题:

I have a shell script in which I would like to prompt the user with a dialog box for inputs when the script is executed.

example (after script has started) :

"Enter the files you would like to install : "

user input : spreadsheet json diffTool

where $1 = spreadsheet, $2 = json, $3 = diffTool

then loop through each user input and do something like

for var in "$@"
do
    echo "input is : $var"
done

How would I go about doing this within my shell script?

Thank you in advance

回答1:

You need to use the read built-in available in bash and store the multiple user inputs into variables,

read -p "Enter the files you would like to install: " arg1 arg2 arg3

Give your inputs separated by space. For example, when running the above,

Enter the files you would like to install: spreadsheet json diffTool

now each of the above inputs are available in the variables arg1,arg2 and arg3


The above part answers your question in way, you can enter the user input in one go space separated, but if you are interested in reading multiple in a loop, with multiple prompts, here is how you do it in bash shell. The logic below get user input until the Enter key is pressed,

#!/bin/bash

input="junk"
inputArray=()

while [ "$input" != "" ] 
do 
   read -p "Enter the files you would like to install: " input
   inputArray+=("$input")
done

Now all your user inputs are stored in the array inputArray which you can loop over to read the values. To print them all in one shot, do

printf "%s\n" "${inputArray[@]}"

Or a more proper loop would be to

for arg in "${inputArray[@]}"; do
    [ ! -z "$arg" ] && printf "%s\n" "$arg"
done

and access individual elements as "${inputArray[0]}", "${inputArray[1]}" and so on.