Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prompt user for input in shell script? [duplicate]

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?

like image 560
danynl Avatar asked Feb 25 '17 07:02

danynl


People also ask

How do you prompt for input from user in Linux shell script?

You can use the built-in read command ; Use the -p option to prompt the user with a question.

What is $@ in script?

$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

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.

like image 88
Inian Avatar answered Oct 09 '22 04:10

Inian