I want to write a bash script that will get user input and store it in an array. Input: 1 4 6 9 11 17 22
I want this to be saved as array.
But we can take array input by using the method of the Scanner class. To take input of an array, we must ask the user about the length of the array. After that, we use a Java for loop to take the input from the user and the same for loop is also used for retrieving the elements from the array.
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.
bash [filename] runs the commands saved in a file. $@ 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.
read it like this:
read -a arr
read -a arr <<< "1 4 6 9 11 17 22"
print # of elements in array:
echo ${#arr[@]}
OR loop through the above array
for i in ${arr[@]}
do
echo $i # or do whatever with individual element of the array
done
Here's my 2 cents.
#!/bin/sh
read -p "Enter server names separated by 'space' : " input
for i in ${input[@]}
do
echo ""
echo "User entered value :"$i # or do whatever with individual element of the array
echo ""
done
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