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
echo
this way makes much more sense, btw I tried everything with quotes and the result was the same, this worked for meslc=(${arr[@]:0:3})
– Nickotine May 29 '23 at 18:11slc=(${arr[@]:0:3})
invokes split+glob which doesn't make sense whatsoever here. See also Security implications of forgetting to quote a variable in bash/POSIX shells and When is double-quoting necessary? for instance for details. – Stéphane Chazelas May 29 '23 at 18:15