Interview Prep/Shell Scripting/Troubleshooting: syntax, parsing and interpreter errors

`bash: local: can only be used in a function`

BeginnerTroubleshootingTroubleshooting: syntax, parsing and interpreter errors
Answer

Likely causes → local used at the top level of a script, often after moving code out of a function, or in a file that is sourced at top level.

Diagnose → Find the line in the error and check whether it is inside a function body.

Fix → Remove local for top-level variables, or wrap the code in a function (main() { ...; }; main "$@"), which is better practice anyway.

Prevent → Keep all logic in functions with a single main "$@" call at the bottom.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: syntax, parsing and interpreter errors