0

I want to "split" an array (in Bash) to a sub-array while retaining all the array-like properties. Apparently, what I have tried has reduced the array to a string.

myscript.sh
#!/bin/bash
A=('foo' 'bar' 'bat' 'baz')
B=${A[@]:0:2} # Get first half of array

for i in ${!B[@]}; do
  echo "B[$i]: ${B[$i]}" # result: B[0]: foo bar
done
The result of this code is:
B[0]: foo bar
But the result I seek is:
B[0]: foo
B[1]: bar

What can I do to retain the array properties in B that will allow me to properly loop thru its elements?

4

1 Answer 1

3
A=('foo 123' 'bar 123' 'bat 123' 'baz 123')
B=("${A[@]:0:2}")
declare -p B

Output:

declare -a B='([0]="foo 123" [1]="bar 123")'
Sign up to request clarification or add additional context in comments.

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.