Skip to content

Latest commit

 

History

History

scripting

Introduction to shell scripting

Good practices

Sometimes we use "write only" Bash scripts that are not to be reused, read by anyone, or maintained. For any other scripts, we should follow some good practices.

An option like x can be toggled with set -x (on) and set +x (off). Combine options like -evx.

  • Don’t include parameters in the shebang: prefer !/bin/bash over !/bin/bash -foo, so that the script still can be called as bash script.

  • For an executable script, start with an appropriate shebang and set executable rights. No need to use .sh extension.

  • File naming conventions for scripts: use snake_case or kebab-case, but be consistent.

  • For a library of functions, don’t include shebang, don’t set executable rights, use .sh extension.

  • After the shebang, include comments about what the script does.

  • Define global variables at the beginning.

  • Define functions after the global variables.

  • Each function should be accompanied by a comment with the following information:

    • function purpose,

    • list of expected arguments,

    • list of possible return codes,

    • whether the function writes to STDOUT / STDERR.

  • Use local variables inside functions.

Common pitfalls

  • Make sure your script handles correctly files:

    • when filename contains spaces and other special characters,

    • when filename starts with - and may be confused with a command option.

As a rule of thumb, we avoid such filenames but don’t hurt users who use them.

  • Make sure your script runs correctly if it is not called from its directory. E.g. if it uses relative paths, it can mess up files when called in an unexpected way.

  • Print error information to STDERR instead of STDOUT.