2
# Create array
arrayLong=(one two three four)
for element in "${arrayLong[@]}"
do
    echo "$element"
done
echo "${#arrayLong[@]}"

Output:

one
two
three
four
4

Then:

# Make new array with only first half of values
arrayShort=("${arrayLong[@]:0:2}")
for element in "${arrayShort[@]}"
do
    echo "$element"
done
echo "${#arrayShort[@]}"

The output of this is

one two
1

Why is my short array not actually an array? It's just one element. How can I split my array when the results are full on arrays?

My bash version is GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16)

  • 1
    It works as it should for me. Try not quoting arrayLong though, like: arrayShort=(${arrayLong[@]:0:2}). Can you also post the output of: echo "${IFS@Q}" – Jesse_b Sep 22 '17 at 23:02
  • 3
    What's your bash version? – glenn jackman Sep 22 '17 at 23:17
  • 1
    GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16) – teradyl Sep 22 '17 at 23:47
  • 1
    @teradyl I'm running the same version (under macOS 10.12.5), and I get "2" for the length of arrayShort. Try declare -p arrayShort and see what that says (I get declare -a arrayShort='([0]="one" [1]="two")'). – Gordon Davisson Sep 23 '17 at 3:33
  • 2
    Based on his output I think it's safe to say that his arrayShort is declare -a arrayShort='([0]="one two")'. My suspicion is that his IFS does not include a space. – Jesse_b Sep 23 '17 at 10:28
3

I was unaware that IFS does not reset automatically after using it. Earlier in the code, I had set the IFS=$'\n' without storing the original value. Here's what I should have done:

# set Internal Field Separator to new line only to split files
oIFS="$IFS"
IFS=$'\n'
array=(${all_files})
# Return IFS to initial value
IFS="$oIFS"

To double check what the IFS is at a given moment, try printf "%q\n" "$IFS". The default value should be $' \t\n'

Thanks @MiniMax & @Jesse_b for helping with this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.