Back to Blog

Zsh Shell Tutorial 11: Functions — Arguments, Return Values & Scope

Sandy LaneSandy Lane

Video: Zsh Shell Tutorial 11: Functions — Arguments, Return Values & Scope by Taught by Celeste AI - AI Coding Coach

Watch full page →

Zsh Shell Tutorial 11: Functions — Arguments, Return Values & Scope

In this tutorial, you'll learn how to create and use functions in Zsh, including defining them with different syntaxes, passing arguments, handling return values, and managing variable scope. Understanding these concepts will help you write cleaner, reusable shell scripts with controlled side effects.

Code

# Define a function using shorthand syntax
greet() {
  echo "Hello, $1!"   # $1 is the first argument passed to the function
}

# Define a function using the 'function' keyword
function add_numbers {
  local sum=$(( $1 + $2 ))  # local variable to avoid polluting global scope
  echo $sum                 # output the result
  return 0                  # return status code 0 indicates success
}

# Call the greet function with an argument
greet "World"

# Capture output of add_numbers function using command substitution
result=$(add_numbers 5 7)
echo "Sum is: $result"

# Demonstrate return status code
function check_even {
  if (( $1 % 2 == 0 )); then
    return 0   # success if even
  else
    return 1   # failure if odd
  fi
}

check_even 4
if [[ $? -eq 0 ]]; then
  echo "4 is even"
else
  echo "4 is odd"
fi

# Show that local variables do not affect global scope
function demo_scope {
  local var="local value"
  echo "Inside function: $var"
}
var="global value"
demo_scope
echo "Outside function: $var"

Key Points

  • Functions can be defined using shorthand syntax (name()) or the function keyword.
  • Arguments inside functions are accessed via positional parameters like $1, $2, $@, and $#.
  • Use return to set an exit status code; 0 means success, non-zero indicates failure.
  • Capture function output with command substitution $(function_name args) to use returned data.
  • Declare variables local inside functions with local to avoid overwriting global variables.