markdown Shell脚本最佳实践

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Shell脚本最佳实践相关的知识,希望对你有一定的参考价值。


## From the top
```
#!/usr/bin/env bash

set -o errexit 
set -o pipefail
```

First line (shebang) tell us which interpreter to use. We recommend using `#!/usr/bin/env bash` for [portability](https://en.wikipedia.org/wiki/Shebang_%28Unix%29#Portability). Different \*nixes put `bash` in different places, so using `/usr/bin/env` is a workaround to find the first `bash` found on the `PATH`. (**Avoid using `sh`**)

Next, you must **always** use a `set -o errexit` or `set -e` for short. This option makes your script exits whenever a command returned with non-zero status code.

`set -o pipefail` help you avoid expression like `error here | true` to be succeed. (This is not what you want)

Some other options are:
* `set -o xtrace` or `set -x` for short: print every expression before execute it. It really helpful when debugging/build script.

## STDOUT vs STDERR
All error messages should go to `STDERR`
Example: `echo "ERROR OCCUR" > &2`

## Variables
To declare new variable, you should use `declare var=value`. 

## Constants
Simply use `readonly var=value`.

## Conditionals
We prefer to user double square brackets `[[ ]]` in statement because those provide cleaner syntax, easy to use.
Inside `[[ ]]` we allowed to user regular expression.

## Command substitution
Use `$(command)` instead of backticks.

## References
* [Shell style guide](https://google.github.io/styleguide/shell.xml)

以上是关于markdown Shell脚本最佳实践的主要内容,如果未能解决你的问题,请参考以下文章

编写Shell脚本的最佳实践,规范一

编写Shell脚本的最佳实践

Linux肝!Shell 脚本编程最佳实践

编写Shell脚本的最佳实践,规范二

知道的都告诉你:编写 Shell 脚本的最佳实践!

想要编写 Shell 脚本的最佳实践?看这篇就够了~