Working with Bash Arrays
array(list)
In Bash, you can represent arrays using parentheses. The delimiter inside is the space bar - pretty simple!
$ cat array_ex.sh
#!/bin/bash
lists=("a" b "c")
echo ${lists[1]}
echo ${lists[0]}
echo ${lists[3]}
echo ${lists[2]}
$ sh array_ex.sh
b
a
c
Notice how lists[3]
returns empty since we only have 3 elements (indices 0, 1, 2). Bash won’t complain - it just gives you nothing, which is actually quite handy for conditional checks.
Slicing is also supported, as shown in the example below:
lists=("V0.1.0" "V1.0.0")
echo "[1] : "${lists[1]}
echo "[0] : "${lists[0]}
echo "[3] : "${lists[3]}
echo "[-1] : "${lists[-1]}
selected=${lists[-1]}
echo "selected : "$selected
The negative indexing [-1]
is pretty cool - it gives you the last element, just like in Python! This makes it super easy to grab the most recent version or the last item without having to calculate the array length.
Pro tip: When working with arrays in Bash, always remember that they’re zero-indexed and space-delimited. If you need comma-separated values, you’ll need to handle that separately or use a different approach.