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?
You can use the built-in read command ; Use the -p option to prompt the user with a question.
$@ 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.
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.
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