| 1 | #!/bin/bash |
| 2 | # neg-array.sh |
| 3 | # Requires Bash, version -ge 4.2. |
| 4 | |
| 5 | array=( zero one two three four five ) # Six-element array. |
| 6 | # 0 1 2 3 4 5 |
| 7 | # -6 -5 -4 -3 -2 -1 |
| 8 | |
| 9 | # Negative array indices now permitted. |
| 10 | echo ${array[-1]} # five |
| 11 | echo ${array[-2]} # four |
| 12 | # ... |
| 13 | echo ${array[-6]} # zero |
| 14 | # Negative array indices count backward from the last element+1. |
| 15 | |
| 16 | # But, you cannot index past the beginning of the array. |
| 17 | echo ${array[-7]} # array: bad array subscript |
| 18 | |
| 19 | |
| 20 | # So, what is this new feature good for? |
| 21 | |
| 22 | echo "The last element in the array is "${array[-1]}"" |
| 23 | # Which is quite a bit more straightforward than: |
| 24 | echo "The last element in the array is "${array[${#array[*]}-1]}"" |
| 25 | echo |
| 26 | |
| 27 | # And ... |
| 28 | |
| 29 | index=0 |
| 30 | let "neg_element_count = 0 - ${#array[*]}" |
| 31 | # Number of elements, converted to a negative number. |
| 32 | |
| 33 | while [ $index -gt $neg_element_count ]; do |
| 34 | ((index--)); echo -n "${array[index]} " |
| 35 | done # Lists the elements in the array, backwards. |
| 36 | # We have just simulated the "tac" command on this array. |
| 37 | |
| 38 | echo |
| 39 | |
| 40 | # See also neg-offset.sh. |