Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux bash script get user input and store in a array

Tags:

linux

bash

shell

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.

like image 714
Vignesh Avatar asked Jun 19 '13 19:06

Vignesh


People also ask

How do you take input from user and store it in an 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.

How can you collect user's input in a bash 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.

What is $@ in bash script?

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.


2 Answers

read it like this:

read -a arr

Test:

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
like image 68
anubhava Avatar answered Oct 25 '22 13:10

anubhava


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
like image 33
vardhan Avatar answered Oct 25 '22 14:10

vardhan