Skip to content

Latest commit

 

History

History
47 lines (32 loc) · 905 Bytes

SC2218.md

File metadata and controls

47 lines (32 loc) · 905 Bytes

Pattern: Calling undefined function

Issue: -

Description

You are calling a function that you are defining later in the file. The function definition must come first.

Function definitions are much like variable assignments, and define a name at the point the definition is "executed". This is why they must happen before their first use.

This is especially apparent when defining functions conditionally:

case "$(uname -s)" in
  Linux) hi() { echo "Hello from Linux"; } ;;
  Darwin) hi() { echo "Hello from macOS"; } ;;
  *) hi() { echo "Hello from something else"; } ;;
esac

hi

Example of incorrect code:

#!/bin/sh
somefunction

somefunction() {
  echo "Hello World"
}

Example of correct code:

#!/bin/sh
somefunction() {
  echo "Hello World"
}
somefunction

Further Reading