When slicing an array the output is captured in a variable as a string.
When the slice is used directly it will be separate items.
How can I save a sliced array in a variable without it being turned into a string?
Any other method or way to go about this?
Example:
# setting IFS to this, no need to quote anything
IFS=$'\n'
mapfile -t arr < <(for i in {1..6}; do echo $i; done)
declare -p arr
declare -a arr=([0]="1" [1]="2" [2]="3" [3]="4" [4]="5" [5]="6")
# $() or `` give the same results
slc=`echo ${arr[@]:0:3}`
# proving that when the slice is saved as a var, it's a string
for i in $slc; do echo $i; done
1 2 3
# proving that when the slice is used directly the items are separate
for i in ${arr[@]:0:3}; do echo $i; done
1
2
3
Got it working with the accepted answer, note; with or without quotes when IFS=$'\n'
the results are the same:
IFS=$'\n'
slc=(${arr[@]:0:3})
for i in ${slc[@]}; do echo $i; done
1
2
3