sriram
sriram

Reputation: 9072

How to get element using array index

I have an array named test which has these contents:

a b c d e f. 

I got these array from string which has :

a/b/c/d/e/f

I split the above string to an array using this:

test=$(echo $dUrl | tr "/" "\n")

Now I wish to get the test's first element using ${test[1]}, but its giving me nothing.

Where I'm making the mistake.

Upvotes: 1

Views: 2379

Answers (3)

Édouard Lopez
Édouard Lopez

Reputation: 43419

A Bash only solution would be to use word splitting and IFS for that.

var="a/b/c/d/e/f"
IFS=/; # redefine word-splitting on slash character
arr=( $var ) # use word-splitting :)

A Better Alternative

Using the read built-in is more secure:

var="a/b/c/d/e"
IFS=/ read -rd '' -a arr <<<"$var"
  • -r: disables interpretion of backslash escapes and line-continuation in the read data ;
  • -a <ARRAY>: store in <ARRAY>, read the data word-wise into the specified array instead of normal variables ;
  • -d <DELIM>: recognize <DELIM> as data-end, rather than <newline>.

Test

echo "${arr[0]}" # → a
echo "${arr[1]}" # → b
echo "${arr[2]}" # → c

Upvotes: 3

jlliagre
jlliagre

Reputation: 30873

test is not an array but a multiline string in your script, one way to get an element (eg the second) would be:

echo "$test" | sed -n '2p'

If you want to build a real array, you can use that syntax:

typeset -a test=( $(echo $dUrl|tr "/" " ") )

Then, ${test[2]} whill show you the second element as you expect.

Upvotes: 2

rjv
rjv

Reputation: 6776

You have to convert a string to array before you index it.

Like

arr=($test)
echo ${arr[2]}

As per your question

$ dUrl="a/b/c/d/e/f"
$ test=$(echo $dUrl | tr "/" "\n")
$ echo $test
a b c d e f
$ a=($test)
$ echo ${a[1]}
b

Upvotes: 2

Related Questions