Help: Bad array subscript
perara-chen opened this issue · 2 comments
perara-chen commented
Please fill out this template
Error accessing last element from an array
Additional context
I'm having problem when accessing the last item from an array. I followed exactly the same as written in the book. Can someone explain me if I did something wrong? Thanks.
My script:
#!/bin/bash
my_array=("value 1" "value 2" "value 3" "value 4")
# Access item 1
echo ${my_array[1]}
# Access the last item
echo ${my_array[-1]}
# Access all the items
echo ${my_array[@]}
# Output total number of elements in the array
echo ${#my_array[@]}
Shell output:
value 2
script1.sh: line 9: my_array: bad array subscript
value 1 value 2 value 3 value 4
4
bobbyiliev commented
Hi there,
What version of bash are you using?
bash --version
Note that unsetting with negative index were only added in bash 4.3.
perara-chen commented
Thank you @bobbyiliev. Your pointer solved the problem. I forgot that I was using Apple's age-old bash. I ran the script on my Linux VM with bash 5.1.8 and everything worked well and the problem is solved. Thank you.
Apple's bash
GNU bash, version 3.2.57(1)-release (arm64-apple-darwin22)
Copyright (C) 2007 Free Software Foundation, Inc.
Script
#!/bin/bash
my_array=("value 1" "value 2" "value 3" "value 4")
# Access item 1
echo ${my_array[1]}
# Access the last item
echo ${my_array[-1]}
# Access all the items
echo ${my_array[@]}
# Output total number of elements in the array
echo ${#my_array[@]}
Output
value 2
value 4
value 1 value 2 value 3 value 4
4