LinuxCommandLibrary

function

Define and name reusable code blocks

TLDR

Define a function with the specified name

$ function [func_name] { [echo "Function contents here"]; }
copy

Run a function named func_name
$ func_name
copy

Define a function without the function keyword
$ [func_name]() { [echo "Function contents here"]; }
copy

Display help
$ help function
copy

SYNOPSIS

function name [()] {
  commands
}

name() {
  commands
}

DESCRIPTION

In Bash and compatible shells like ksh and zsh, the function keyword defines shell functions—named blocks of code executed like commands for modularity and reuse in scripts or interactive sessions.

Functions encapsulate logic, accept arguments via $1, $2, etc., and return status codes (0-255) via return or exit. Use local for variables scoped to the function. They support recursion and can call other functions.

Defined functions persist in the current shell until unset -f name or shell exit. Export with export -f name for subshell inheritance. List with declare -f or typeset -f.

This enhances scripting beyond aliases, enabling complex logic like loops and conditionals. Prefer the portable name() syntax over function for broader compatibility.

CAVEATS

Non-POSIX; function keyword unsupported in strict /bin/sh. Use name() form for portability.
Conflicts with existing commands/builtins shadow them.

BASIC EXAMPLE

function greet {
  echo "Hello, $1!"
}

greet Alice # Hello, Alice!

WITH ARGUMENTS AND LOCAL VAR

function sum {
  local total=$(( $1 + $2 ))
  echo $total
}

sum 5 3 # 8

HISTORY

Originated in KornShell (ksh88, 1988); Bash adopted in v1.0 (1989). POSIX.1-2008 mandates name() without function. Evolved for recursion, exporting in later Bash versions.

SEE ALSO

bash(1), ksh(1), declare(1), typeset(1), unset(1)

Copied to clipboard