I'm learning Bash and found an older guide to defensive scripting. Are there more current resources or practices worth following?
Also, if a script needs a lot of checks and extra code to be robust, is Bash still a reasonable choice?
I'm learning Bash and found an older guide to defensive scripting. Are there more current resources or practices worth following?
Also, if a script needs a lot of checks and extra code to be robust, is Bash still a reasonable choice?
The BashGuide and Bash Pitfalls are useful references, and ShellCheck is a good tool to run against your scripts. The Google Shell Style Guide is another perspective, though its rules reflect a particular team's preferences rather than universal Bash law.
Read older guides critically too. A useful explanation can sit right next to an example with unsafe quoting or questionable argument handling.
Two things to watch for early on: quote variable expansions when you want to preserve a value as one argument, and use the quoted form "$@" to pass arguments along without losing their boundaries. Packing all the arguments into a single scalar makes it hard to recover arguments that contain spaces.
Also consider values beginning with a dash. Many commands accept -- to mark the end of options, which can keep a filename from being treated as a flag. Check the command's documentation, since not every command supports it.
Short script doesn't have to mean fewest lines. Make the intent easy to follow, use consistent patterns, and comment on why something nonobvious is happening. A dense one-liner can be much harder to maintain than a few clear steps.
That said, extra words aren't automatically clearer. A comment that merely repeats an obvious assignment or increment just adds noise.
Checks are useful when they cover real failure cases. Think about what happens if a command fails, its output isn't what you expected, or a file can't be read or written. For scripts other things depend on, add tests too.
If the control flow and error handling start taking over the script, consider Python or another more structured language. There's no magic line count that settles it, but some style guides suggest switching once shell code gets large or complicated.
Answers are reviewed before publication.
8q+papercrank_361:
And if you need to save the arguments for later, a Bash array can preserve them as separate values.