Live data from Hacker News

Shell script best practices, from a decade of scripting things

sharats.me

1–10 of 500 posts

Re: Shell script best practices, from a decade of scripting things

#6
For systems that I control myself I much prefer to avoid Bash/sh. They’re just to clunky. And if I need to use them, I try to do as little as possible in order to make it more robust.

Case 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

#10
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.
Post reply on HN