Skip to content

Shellcheck

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

개별적인 Redirect는 { cmd1; cmd2; } >> file 형식으로 한 번에 묶어서 하자.

Problematic code:

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

Correct code:

{
  echo foo
  date
  cat stuff
} >> file

SC2155

반환 값을 마스킹 하지 않도록 별도로 선언하고 할당합니다.

문제 코드:

export foo="$(mycmd)"

올바른 코드:

foo="$(mycmd)"
export foo

문제 코드에서 mycmd의 반환 값은 무시되고, export는 항상 true를 반환합니다. 이는 여러 조건문을 막고, set -e 트랩이 올바르게 작동 하지 않을 수 있습니다.

비슷한 문제로 localreadonly도 분리해야 한다:

문제가 되는 코드:

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

올바른 코드:

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

SC2164

cd가 실패할 수 있으니 cd ... || exit를 사용.

RECC_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")"; pwd)  # Bad
RECC_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" || exit; pwd)  # Good

SC2181

$? -ne 0 와 같이 비교하지 말고 if 명령 안에 해당 명령을 입력해라.

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