Skip to content

Functions

  • functions can be terminated using return OR exit

    • in Bash, return does not pass a data value like in C++ or Java; it only passes an exit status code (a number between 0 and 255).

      Terminal window
      check_network() {
      ping -c 1 google.com > /dev/null 2>&1
      if [ $? -eq 0 ]; then
      return 0 # Success
      else
      return 1 # Failure
      fi
      }
      RiskExplanation
      The 255 LimitExit codes are 8-bit integers. If your math result is 256, return will give you 0. If it is 257, it gives you 1. It “wraps around”.
      Status vs. DataIn Linux, 0 usually means “Success” and non-zero means “Error”. Using return for math flips this logic and can confuse other parts of your script.
      Immediate CaptureYou must use $? immediately. If you run any other command (even an echo) between the function call and $?, the value will be overwritten by the new command’s status.
  • local used to define local variables inside function which are different from outside variables..

    • TIP: if we try to access a variable in bash which is not defined.. we won’t get any errors!!! instead it prints empty value..
  • We can’t directly access inner function of a function! first we have to call outer-function which then defines inner function for global access..

image.png

image.png

image.png

  • name() { ... }: Standard syntax; the most portable and common way to define a function.

  • function name { ... }: Alternative syntax using the function keyword; parentheses are optional here.

  • function name() { ... }: Combined syntax; works in Bash but is redundant.

  • name() { command; }: Single-line syntax; requires a space after { and a semicolon before }.

  • local var=$1: Variable scope limiter; restricts a variable’s existence to the function execution.

  • $1, $2, ... $n: Positional parameters; accesses arguments passed to the function by their order.

  • $#: Argument counter; returns the total number of arguments passed to the function.

  • $@: All-arguments list; represents every passed argument as a distinct quoted string.

  • return n: Exit status; stops the function and returns a numeric code (0–255) to the caller.

  • $(name): Command substitution; captures the echo output of a function into a variable.

  • name() { ... } > file: Function redirection; sends all standard output from the function into a specific file.

  • outer() { inner() { ... }; }: Nested definition; defines a function inside another (inner becomes global once outer runs).

    Terminal window
    parent_func() {
    echo "This is the parent."
    child_func() {
    echo "This is the child, nested inside."
    }
    child_func # Calling it inside the parent
    }
    # child_func # This would fail here (not defined yet)
    parent_func # Runs parent and defines child
    child_func # Now this works globally!

Example

image.png

image.png