SC2104 – ShellCheck Wiki

See this page on GitHub

Sitemap


In functions, use return instead of break.

Problematic code:

foo() {
  if [[ -z $1 ]]
  then
    break
  fi
  echo "Hello $1"
}

Correct code:

foo() {
  if [[ -z $1 ]]
  then
    return 1
  fi
  echo "Hello $1"
}

Rationale:

break or continue are used to abort or continue a loop, and are not the right way to exit a function. Use return instead.

Exceptions:

The break or continue may be intended for a loop that calls the function:

# Rarely valid
foo() { break; echo $?; }
while true; do foo; done

This is undefined behavior in POSIX sh. Different shells do different things.

When the function is called from a loop:

When the function is not called from a loop:

Due to the many different implementations, many of which are not helpful, it's recommended to use proper flow control. A typical solution is making sure the function returns success/failure, and calling myfunction || break in the loop.


ShellCheck is a static analysis tool for shell scripts. This page is part of its documentation.