Shellcheck
lastmod 2023-03-02created 2021-12-0311 edits
ShellCheck, a static analysis tool for shell scripts
SC2025
Make sure all escape sequences are enclosed in $$ .. $$ to prevent line wrapping issues.
Problematic code:
Correct code:
Rationale
Bash is unable to determine exactly which parts of your prompt are text and which are terminal codes. You have to help it by wrapping invisible control codes in $$ .. $$ (and ensuring that visible characters are not wrapped in $$ .. $$ ).
| NOTE |
| ShellCheck offers this as a helpful hint and not a robust check. Don't rely on ShellCheck to verify that your prompt is correct. |
SC2129
Group individual redirects together at once in the form { cmd1; cmd2; } >> file.
Problematic code:
Correct code:
SC2155
Declare and assign separately to avoid masking return values.
Problematic code:
Correct code:
In the problematic code, the return value of mycmd is ignored, and export always returns true. This can block various conditionals, and set -e traps may not work correctly.
For the same reason, local and readonly should also be separated:
Problematic code:
Correct code:
SC2164
cd can fail, so use cd ... || exit.
RECC_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")"; pwd) # Bad
RECC_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" || exit; pwd) # Good
SC2181
Don't compare like $? -ne 0; put the command directly inside the if command.
Problematic code:
Correct code:
See also
- shell
- bash
- sh
- ShellSpec - full-featured BDD unit testing framework
- shellcheck - ShellCheck, a static analysis tool for shell scripts
- shfmt - A shell parser, formatter, and interpreter with bash support
- Explainshell - match command-line arguments to their help text