Shell script best practices, from a decade of scripting things
1–10 of 500 posts
Re: Shell script best practices, from a decade of scripting things
#2Re: Shell script best practices, from a decade of scripting things
#3Re: Shell script best practices, from a decade of scripting things
#4Re: Shell script best practices, from a decade of scripting things
#5Personally I try to stick with POSIX sh (testing with dash), if I need anything fancier, I reach for Perl or Python.
Re: Shell script best practices, from a decade of scripting things
#6Case in point: Declaring an array. IMHO, it’s just not ergonomic at all. Especially not in sh/dash.
Re: Shell script best practices, from a decade of scripting things
#7Re: Shell script best practices, from a decade of scripting things
#8These could be linting rules for bash script files.
Re: Shell script best practices, from a decade of scripting things
#9Re: Shell script best practices, from a decade of scripting things
#10As soon as output needs to be parsed — especially when it’s being fed back into other parts of the script — it gets harder. Handling errors and exceptions is even more difficult.
Things really fall down on modularity. There are tricks and conventions: for example you can put all functions to do with x in a file called lib/x.sh, prefix them all with x_, and require that all positional parameters must be declared at the top of each function with local names.
At that point though, I would rather move to a language with named parameters, namespaced modules, and exception handling. In Python, it’s really easy to do the shell bits with:
def sh(script):
subprocess.run(
[‘sh’, ‘-c’, script, ‘--‘, *args],
check=True,
)
which will let you pass in arguments with spaces and be able to access them as properly lexed arguments in $1, $2 etc in your script. You can even preprocess the script to be prefixed with all the usual set -exuo pipefail stuff etc.