项目作者: icy

项目描述 :
A Bash coding style
高级语言:
项目地址: git://github.com/icy/bash-coding-style.git
创建时间: 2015-03-21T15:35:37Z
项目社区:https://github.com/icy/bash-coding-style

开源协议:

下载


Some Bash coding conventions and good practices.

Coding conventions are… just conventions.
They help to have a little fun with scripting,
not to create new war/bias conversations.

Feel free to break the rules any time you can; it’s important
that you will always love what you would have written
because scripts can be too fragile, too hard to maintain,
or so many people hate them…
And it’s also important to have a consistent way in your scripts.

Naming and Styles

Tabs and Spaces

Don’t use (smart-)tabs. Replace a tab by two spaces.
Do not accept any trailing spaces.

Many editors can’t and/or aren’t configured to display the differences
between tabs and spaces. Another person’s editor is just not your editor.
Having spaces does virtually help a strange reader of your script.

Pipe

There are inline pipe and display pipe. Unless your pipe is
short, please use display pipe to make things clear. For example,

  1. # This is an inline pipe: "$(ls -la /foo/ | grep /bar/)"
  2. # The following pipe is of display form: every command is on
  3. # its own line.
  4. foobar="$( \
  5. ls -la /foo/ \
  6. | grep /bar/ \
  7. | awk '{print $NF}')"
  8. _generate_long_lists \
  9. | while IFS= read -r line; do
  10. _do_something_fun
  11. done

When using display form, put pipe symbol (|) at the beginning of
of its statement. Don’t put | at the end of a line, because it’s the
job of the line end (EOL) character and line continuation (\).

Here is another example

  1. # List all public images found in k8s manifest files
  2. # ignore some in-house image.
  3. list_public_images() {
  4. find . -type f -iname "*.yaml" -exec grep 'image: ' {} \; \
  5. | grep -v ecr. \
  6. | grep -v '#' \
  7. | sed -e "s#['\"]##g" \
  8. | awk '{print $NF}' \
  9. | sort -u \
  10. | grep -Eve '^(coredns|bflux|kube-proxy|logstash)$' \
  11. }

Variable names

If you are going to have meanful variable name, please use them
for the right purpose. The variable name country_name should
not be used to indicate a city name or a person, should they?
So this is bad

  1. countries="australia germany berlin"
  2. for city in $countries; do
  3. echo "city or country is: $city
  4. done

That’s very bad example but that is to emphasize the idea.
(FIXME: Add better examples)

A variable is named according to its scope.

  • If a variable can be changed from its parent environment,
    it should be in uppercase; e.g, THIS_IS_A_USER_VARIABLE.
  • Other variables are in lowercase
  • Any local variables inside a function definition should be
    declared with a local statement.

Example

  1. # The following variable can be provided by user at run time.
  2. D_ROOT="${D_ROOT:-}"
  3. # All variables inside `my_def` are declared with `local` statement.
  4. my_def() {
  5. local d_tmp="/tmp/"
  6. local f_a=
  7. local f_b=
  8. # This is good, but it's quite a mess
  9. local f_x= f_y=
  10. }

Though local statement can declare multiple variables, that way
makes your code unreadable. Put each local statement on its own line.

FIXME: Add flexibility support.

Function names

Name of internal functions should be started by an underscore (_).
Use underscore (_) to glue verbs and nouns. Don’t use camel form
(ThisIsNotMyStyle; use this_is_my_style instead.)

Use two underscores (__) to indicate some very internal methods aka
the ones should be used by other internal functions.

Error handling

Sending instructions

All errors should be sent to STDERR. Never send any error/warning message
to aSTDOUT device. Never use echo directly to print your message;
use a wrapper instead (warn, err, die,…). For example,

  1. _warn() {
  2. echo >&2 ":: $*"
  3. }
  4. _die() {
  5. echo >&2 ":: $*"
  6. exit 1
  7. }

Do not handle error of another function. Each function should handle
error and/or error message by their own implementation, inside its own
definition.

  1. _my_def() {
  2. _foobar_call
  3. if [[ $? -ge 1 ]]; then
  4. echo >&2 "_foobar_call has some error"
  5. _error "_foobar_call has some error"
  6. return 1
  7. fi
  8. }

In the above example, _my_def is trying to handle error for _foobar_call.
That’s not a good idea. Use the following code instead

  1. _foobar_call() {
  2. # do something
  3. if [[ $? -ge 1 ]]; then
  4. _error "${FUNCNAME[0]} has some internal error"
  5. fi
  6. }
  7. _my_def() {
  8. _foobar_call || return 1
  9. }

Catch up with $?

$? is used to get the return code of the last statement.
To use it, please make sure you are not too late. The best way is to
save the last return code thanks to some local variable. For example,

  1. _do_something_critical
  2. local _ret="$?"
  3. # from now on, $? is zero, because the latest statement (assignment)
  4. # (always) returns zero.
  5. _do_something_terrible
  6. echo "done"
  7. if [[ $? -ge 1 ]]; then
  8. # Bash will never reach here. Because "echo" has returned zero.
  9. fi

$? is very useful. But don’t trust it.

Please don’t use $? with set -e ;)

Pipe error handling

Pipe stores its components’ return codes in the PIPESTATUS array.
This variable can be used only ONCE in the sub-{shell,process}
followed the pipe. Be sure you catch it up!

  1. echo test | fail_command | something_else
  2. local _ret_pipe=( "${PIPESTATUS[@]}" )
  3. # from here, `PIPESTATUS` is not available anymore

When this _ret_pipe array contains something other than zero,
you should check if some pipe component has failed. For example,

  1. # Note:
  2. # This function only works when it is invoked
  3. # immediately after a pipe statement.
  4. _is_good_pipe() {
  5. echo "${PIPESTATUS[@]}" | grep -qE "^[0 ]+$"
  6. }
  7. _do_something | _do_something_else | _do_anything
  8. _is_good_pipe \
  9. || {
  10. echo >&2 ":: Unable to do something"
  11. }

Automatic error handling

Set -u

Always use set -u to make sure you won’t use any undeclared variable.
This saves you from a lot of headaches and critical bugs.

Because set -u can’t help when a variable is declared and set to empty
value, don’t trust it twice.

It’s recommended to emphasize the needs of your variables before your
script actually starts. In the following example, the script just stops
when SOME_VARIABLE or OTHER_VARIABLE is not defined; these checks
are done just before any execution of the main routine(s).

  1. : a lot of method definitions
  2. set -u
  3. : "${SOME_VARIABLE}"
  4. : "${OTHER_VARIABLE}"
  5. : your main routine

Set -e

Use set -e if your script is being used for your own business.

Be careful when shipping set -e script to the world. It can simply
break a lot of games. And sometimes you will shoot yourself in the foot.
If possible please have an option for user choice.

Let’s see

  1. set -e
  2. _do_some_critical_check
  3. if [[ $? -ge 1 ]]; then
  4. echo "Oh, you will never see this line."
  5. fi

If _do_some_critical_check fails, the script just exits and the following
code is just skipped without any notice. Too bad, right? The code above
can be refactored as below

  1. set +e
  2. if _do_some_critical_check; then
  3. echo "Something has gone very well."
  4. fi
  5. echo "You will see this line."

Now, if you expect to stop the script when _do_some_critical_check fails
(it’s the purpose of set -e, right?), these lines don’t help. Why?
Because set -e doesn’t work when being used with if. Confused?
Okay, these lines are the correct one

  1. set +e
  2. if _do_some_critical_check; then
  3. echo "All check passed."
  4. else
  5. echo "Something wrong we have to stop here"
  6. exit 1 # or return 1
  7. fi

set -e doesn’t help to improve your code: it just forces you to work hard,
doesn’t it?

Another example, in effect of set -e:

  1. (false && true); echo not here

prints nothing, while:

  1. { false && true; }; echo here

prints here.

The result is varied with different shells or even different versions of the same shell.

In general, don’t rely on set -e and do proper error handling instead.

For more details about set -e, please read

The correct answer to every exercise is actually “because set -e is crap”.

Techniques

Keep that in mind

There are lot of shell scripts that don’t come with (unit)tests.
It’s just not very easy to write tests. Please keep that in mind:
Writing shell scripts is more about dealing with runtime and side effects.

It’s very hard to refactor shell scripts.
Be prepared, and don’t hate bash/shell scripts too much ;)

A little tracing

It would be very helpful if you can show in your script logs some tracing
information of the being-invoked function/method.

Bash has two jiffy variables LINENO and FUNCNAME that can help.
While it’s easy to understand LINENO, FUNCNAME is a little complex.
It is an array of chained functions. Let’s look at the following example

  1. funcA() {
  2. log "This is A"
  3. }
  4. funcB() {
  5. log "This is B"
  6. funcA
  7. }
  8. funcC() {
  9. log "This is C"
  10. funcB
  11. }
  12. : Now, we call funcC
  13. funcC

In this example, we have a chain: funcC -> funcB -> funcA.
Inside funcA, the runtime expands FUNCNAME to

  1. FUNCNAME=(funcA funcB funcC)

The first item of the array is the method per-se (funcA),
and the next one is the one who instructs funcA (it is funcB).

So, how can this help? Let’s define a powerful log function

  1. log() {
  2. echo "(LOGGING) ${FUNCNAME[1]:-unknown}: *"
  3. }

You can use this little log method everywhere, for example, when funcB
is invoked, it will print

  1. LOGGING funcB: This is B

Making your script a library

First thing first: Use function if possible. Instead of writting
some direct instructions in your script, you have a wrapper for them.
This is not good

  1. : do something cool
  2. : do something great

Having them in a function is better

  1. _default_tasks() {
  2. : do something cool
  3. : do something great
  4. }

Now in the very last lines of you script, you can execute them

  1. case "${@:-}" in
  2. ":") echo "File included." ;;
  3. "") _default_tasks ;;
  4. esac

From other script you can include the script easily without executing
any code:

  1. # from other script
  2. source "/path/to_the_previous_script.sh" ":"

(When being invoked without any argument the _default_tasks is called.)

By advancing this simple technique, you have more options to debug
your script and/or change your script behavior.

Quick self-doc

It’s possible to generate beautiful self documentation by using grep,
as in the following example. You define a strict format and grep them:

  1. _func_1() { #public: Some quick introduction
  2. :
  3. }
  4. _func_2() { #public: Some other tasks
  5. :
  6. }
  7. _quick_help() {
  8. LANG=en_US.UTF_8
  9. grep -E '^_.+ #public' "$0" \
  10. | sed -e 's|() { #public: |☠|g' \
  11. | column -s"☠" -t \
  12. | sort
  13. }

When you execute _quick_help, the output is as below

  1. _func_1 Some quick introduction
  2. _func_2 Some other tasks

No excuse

When someone tells you to do something, you may blindly do as said,
or you would think twice then raise your white flag.

Similarly, you should give your script a white flag. A backup script
can’t be executed on any workstation. A clean up job can’t silently
send rm commands in any directory. Critical mission script should

  • exit immediately without doing anything if argument list is empty;
  • exit if basic constraints are not established.

Keep this in mind. Always.

Meta programming

Bash has a very powerful feature that you may have known:
It’s very trivial to get definition of a defined method. For example,

  1. my_func() {
  2. echo "This is my function`"
  3. }
  4. echo "The definition of my_func"
  5. declare -f my_func
  6. # <snip>

Why is this important? Your program manipulates them. It’s up to your
imagination.

For example, send a local function to remote and excute them via ssh

  1. {
  2. declare -f my_func # send function definition
  3. echo "my_func" # execution instruction
  4. } \
  5. | ssh some_server

This will help your program and script readable especially when you
have to send a lot of instructions via ssh. Please note ssh session
will miss interactive input stream though.

Removing with care

It’s hard to remove files and directories correctly.
Please consider to use rm with backup options. If you use some
variables in your rm arguments, you may want to make them immutable.

  1. export temporary_file=/path/to/some/file/
  2. readonly temporary_file
  3. # <snip>
  4. rm -fv "$temporary_file"

Shell or Python/Ruby/etc

In many situations you may have to answer to yourself whether you have
to use Bash and/or Ruby/Python/Go/etc.

One significant factor is that Bash doesn’t have a good memory.
That means if you have a bunch of data (in any format) you probably
reload them every time you want to extract some portion from them.
This really makes your script slow and buggy. When your script
needs to interpret any kind of data, it’s a good idea to move forward
and rewrite the script in another language, Ruby/Python/Golang/....

Anyway, probably you can’t deny to ignore Bash:
it’s still very popular and many services are woken up by some shell things.
Keep learning some basic things and you will never have to say sorry.
Before thinking of switching to Python/Ruby/Golang, please consider
to write better Bash scripts first ;)

Contributions

Variable names for arrays

In #7, Cristofer Fuentes suggests to use special names for arrays.
Personally I don’t follow this way, because I always try to avoid
to use Bash array (and/or associative arrays), and in Bash
per-se there are quite a lot of confusion (e.g, LINENO is a string,
FUNCNAME is array, BASH_VERSION is … another array.)

However, if your script has to use some array, it’s also possible to
have special name for them. E.g,

  1. declare -A DEPLOYMENTS
  2. DEPLOYMENTS["the1st"]="foo"
  3. DEPLOYMENTS["the2nd"]="bar"

As there are two types of arrays, you may need to enforce a better name

  1. declare -A MAP_DEPLOYMENTS

Well, it’s just a reflection of some idea from another language;)

Good lessons

See also in LESSONS.md (https://github.com/icy/bash-coding-style/blob/master/LESSONS.md).

Deprecation

variable name started with an underscore (_foo_bar)

Deprecated on July 7th 2021 (cf.: https://github.com/icy/bash-coding-style/issues/10).

To migrate existing code, you may need to list all variables that
followed the deprecated convention. Here is an simple grep command:

  1. $ grep -RhEoe '(\$_\w+)|(\$\{_[^}]+\})' . | sort -u
  2. # -R find in all files in the current directory
  3. # -h don't show file name in the command output
  4. # -E enable regular expression
  5. # -o only print variable name that matches our pattern
  6. # -e to specify the pattern (as seen above)

Resources

Authors. License

The original author is Anh K. Huynh and the original work was part of
TheSLinux.

A few contributors have been helped to fix errors and improve the style.
They are also the authors.

The work is released under a MIT license.