Interview Prep/Shell Scripting/Troubleshooting: quoting, expansion and tool-input bugs

`hosts[${#hosts[@]}-1]` style code fails with `bash: hosts: bad array subscript`.

IntermediateTroubleshootingTroubleshooting: quoting, expansion and tool-input bugs
Answer

Likely causes → A negative index that does not exist (${arr[-1]} on an empty array), or arithmetic in the subscript that produces an invalid value because the array is empty.

Diagnose → declare -p hosts to see whether it has elements; check where it is filled (mapfile from a command that returned nothing).

Fix → Guard for empty arrays before indexing:

(( ${#hosts[@]} )) || die "no hosts found"
last=${hosts[-1]}            # Bash 4.3+

Prevent → Treat "command returned nothing" as a case to handle explicitly, not an assumption.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: quoting, expansion and tool-input bugs