bash – How to Use `set` for Setting Shell Options in Google’s Shell Style Guide

bashshell-script

From Google's Shell Style Guide:

Bash is the only shell scripting language permitted for executables.

Executables must start with #!/bin/bash and a minimum number of flags. Use set to set shell options so that calling your script as bash script_name does not break its functionality.

Specifically, the part about using set to avoid breaking functionality. And what does calling it in that particular way have to do with it?

Best Answer

The "and a minimum number of flags" refers to flags set in the hashbang line. They'd be read when the script is started as ./somescript, and the kernel reads the hashbang line, building a new argument list from the path and options found there. But this does not happen if the script is started as bash somescript, as the kernel is asked to run bash, and not the script itself. The shell itself sees the line as a comment to be ignored when eventually reading the script.

For example, try the following script (in ./hello):

#!/bin/bash -x
echo hello

And run it in both of the two ways:

$ ./hello
+ echo hello
hello
$ bash hello
hello

The extra trace output from -x is shown only in the first case, the flag is ignored with the second invocation.

Enabling the flag explicitly with a set command would make it work the same either way:

#!/bin/bash
set -x
echo hello

(though note that if you ever try this with perl, it does interpret the hashbang line itself, too.)

Related Question