BaRud
BaRud

Reputation: 3228

read array element from stdin with space delimited number in bash

I am trying this small piece of code in bash:

echo "Enter number(a b c)"
read natc
echo ${natc[1]}

The input should be 3 number in one line, space delimited, read from stdin, e.g. 4 5 6 and I would like to access them in array,natc[] i.e. natc[0]=4, natc[1]=5 etc.

there are many example in google, but mostly reading the array from a file or predefined value. How can I achieve my goal?

Upvotes: 0

Views: 2361

Answers (2)

anubhava
anubhava

Reputation: 785661

Use -p and -a read options:

read -p "Enter an array: " -a natc
Enter an array: a b c d

echo "${natc[0]}"
a
echo "${natc[1]}"
b
echo "${natc[2]}"
c
echo "${natc[3]}"
d

echo "${#natc[@]}"
4

Upvotes: 3

Kevin
Kevin

Reputation: 56129

You can read into an array with -a:

read -a natc

Upvotes: 5

Related Questions