Following Google's Shell Style
I use Bash scripts quite often for many internal tools. One of the scripts I use everyday now grows to about 300 lines. Its purpose is to auto fetch various internal data (such as multiple JIRAs) and organize the results into one single page, which saves me a lot of time.
I have read the Google Shell Style long ago, and finally got some time during Xmas break to follow the guidelines. Here are the major findings:
Use $(command)
instead of backticks.
Backticks refers to `, for example results=`cmd arg1 arg2`
The reasons not to use backticks anymore are due to
- backticks an be messy and not good for nesting. If you have backticks inside backtick, you would need to escape them. A good example here
libdir=$(dirname $(dirname $(which gcc)))/lib
libdir=`dirname \`dirname \\\`which gcc\\\`\``/lib
- $ is more safe and predictable.
Use (( ... )) or $(( ... )) instead of expr (command).
The reasons not to use expr is, it is simply too old.
For the difference of (( ... )) and $(( ... )) is: the latter (with $) will return the results of the calculation while the former (( ... )) will not, which means $(( ... )) is useful in echo statement.
$ a=2; b=3; echo $((a*b))
6
$ a=3; b=3; ((a==b)) && echo yes
yes
And, use two spaces ! Indentation is two spaces, Whatever you do, don't use tabs!
The reasons for two spaces? None.
But here you go, ladies and gentlemen, this proved Richard is wrong in the argument of tabs vs spaces.
Then I installed the shellcheck tool mentioned by this guideline, and what I found out is
- use grep -c instead of grep xxx | wc -l. It sure is smart to point this out.
- cat is always not needed. Use the filename as augment for the command instead.
Well, according to this guide:
If you are writing a script that is more than 100 lines long, ..., you should rewrite it in a more structured language now
Mine is getting close to 300 and I sure do not foresee a rewrite. but might worth some rework to simplify/reuse some of the logics to reduce the lines in the future.