Skip to content
Search

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:

PS1='\e[36m\$ \e(B\e[m'

Correct code:

PS1='\[\e[36m\]\$ \[\e(B\e[m\]'

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:

echo foo >> file
date >> file
cat stuff  >> file

Correct code:

{
  echo foo
  date
  cat stuff
} >> file

SC2155

Declare and assign separately to avoid masking return values.

Problematic code:

export foo="$(mycmd)"

Correct code:

foo="$(mycmd)"
export foo

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:

local foo="$(mycmd)"
# and ...
readonly foo="$(mycmd)"

Correct code:

local foo
foo=$(mycmd)
# and ...
foo="$(mycmd)"
readonly foo

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:

make mytarget
if [ $? -ne 0 ]; then echo "Build failed"; fi

Correct code:

if ! make mytarget; then echo "Build failed"; fi

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

Favorite site

author Zer0 sitemap