[Bash] Get the last element of an array

Created on November 30, 2026

For an indexed array with consecutive indices starting at zero, subtract one from the element count to get the final index. Check the count before accessing the index so an empty array is handled correctly.

#!/usr/bin/env bash

array=(apple banana cherry)

if ((${#array[@]} > 0)); then
  last_element="${array[${#array[@]} - 1]}"
  echo "$last_element"
fi

Output

cherry

${#array[@]} gives the number of elements. The example checks that this number is greater than zero before looking up the last element.

Bash Shell command