1

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.

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.