`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.
More on Troubleshooting: quoting, expansion and tool-input bugs
`bash: [: too many arguments`Beginner`bash: [: =: unary operator expected`BeginnerA disk check fails with `[: 93%: integer expression expected`Beginner`rm $file` fails with `rm: cannot remove 'monthly': No such file or directory` and `rm: cannot remove 'report.csv'`.BeginnerA cleanup script logs `cp: cannot stat '/var/log/app/*.log': No such file or directory` on quiet days.Beginner`echo "start" > $logfile` fails with `bash: $logfile: ambiguous redirect`Intermediate