Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Writing Robust Bash Shell Scripts (davidpashley.com)
57 points by felipelemos on Nov 22, 2016 | hide | past | favorite | 4 comments



If you are interested in this, you may find ShellCheck a useful tool.

It is a static analyzer for Shell, that looks for some of the problems cited in the post.

https://www.shellcheck.net


This article has some good points, and I was glad to learn about the "trap" command, to clean up temp files on unexpected exit.

There is also a little overlap with this "unofficial bash strict mode," which I now use all the time:

  #!/bin/bash
  set -euo pipefail
  IFS=$'\n\t'
--- http://redsymbol.net/articles/unofficial-bash-strict-mode/


> Be atomic

You can only fool yourself that multiple unrelated operations to the filesystem will be atomic. A more pragmatic approach is to clean up everything at the beginning of the script and start the actual operations with that assumption (and checking the exit status of every command). If the script is interrupted in the middle, just start it again.


Great list. I've encountered almost all of these situations before and it's no fun if your bash script goes berserk.

I would add that you should use an explicit shebang such as #!/bin/bash instead of #!/bin/sh if your script is anything more complicated than a simple list of statements.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: