google / styleguide

Style guides for Google-originated open-source projects

Home Page:https://google.github.io/styleguide/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bash script mode

M4rotte opened this issue · comments

Hi,

Simple question about style guide for Bash:

Is there a reason not to recommend what’s usually called “Bash strict mode”? (I’d call it “Bash script mode” myself)

Which is the fact of writing any Bash script with those four settings (declared in the top of the file):

set -euo pipefail
IFS=$'\n\t'

It implies to change a few habits one may have, but I find this very useful once used to.

A detailed explanation: http://redsymbol.net/articles/unofficial-bash-strict-mode/

we shouldn't encourage people to think turning on set -e means they don't need to add error checking

https://mywiki.wooledge.org/BashFAQ/105

set -u seems a matter of taste. I don't know that it catches bugs that really matter. for typod vars, shellcheck is better imo, especially because it is a static analyzer.

pipefail can be a little insidious. consider tools that exit early like grep -q -- if you were piping a large file to it, it could trigger a write to a closed ("broken") pipe, but not consistently. this is a fun bug to track down.

might be worthwhile adding an appendix on these options and why we don't require them all the time.

we shouldn't encourage people to think turning on set -e means they don't need to add error checking

The errexit option (set -e) clearly doesn’t prevent the need for proper error checking. I would even say it forces people not letting some silent errors here and there. I do not see how it could represent such an encouragement.

More I think about it, not exiting on error only makes sens for an interactive use of Bash, but not for a script. But it is indeed probably not always a good idea to set this option when the script is used. But during the development phase at least it is highly useful imo.

You’re right for the pipefail option. I don’t think it is as important as the errexit and nounset options.

The nounset (set -u), imho, forces user not to let “dead” code that could make the code harder to (re)read, and to always choose default value for any variable.

Thank you for your answers.