Debian Codegraph @

neg-array.sh

raw symbols SCIP
1 #!/bin/bashscip-shell filesystem . . `/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 echoscip-shell system . . echo. ${array[-1]} # five
11 echoscip-shell system . . echo. ${array[-2]} # four
12 # ...
13 echoscip-shell system . . 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 echoscip-shell system . . echo. ${array[-7]} # array: bad array subscript
18
19
20 # So, what is this new feature good for?
21
22 echoscip-shell system . . echo. "The last element in the array is "${array[-1]}""
23 # Which is quite a bit more straightforward than:
24 echoscip-shell system . . echo. "The last element in the array is "${array[${#array[*]}-1]}""
25 echoscip-shell system . . 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 [scip-shell system . . `[`. $index -gt $neg_element_count ]; do
34 ((index--)); echoscip-shell system . . 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 echoscip-shell system . . echo.
39
40 # See also neg-offset.sh.