4 ms·
Shell scripts are great for executing a series of commands with branching and looping logic around them. As soon as output needs to be parsed — especially when
by gorgoiler 4y ago
Shell scripts are great for executing a series of commands with branching and looping logic around them.
As 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.