Working with Functions in Bash: Reference and Examples

Working with Functions in Bash: Reference and Examples

Last updated:
Table of Contents

Function without arguments

function do_something() {
    echo "this gets printed to standard output"
}

# to call it, just use its name
do_something

Access function arguments

$1 is the first argument, $2 is the second argument, etc.

function say_something() {
    echo "$1"
}

Using the function:

  • say_something "foobar" (prints "foobar")

  • say_something (prints nothing because no arguments were passed)

  • say_something foo bar (prints "foo" only, the second argument is not used)

Number of arguments passed

To get the number of arguments sent to the function use $#

myfunction() {
    if [[ $# -eq 0 ]]; then
      # no parameters passed
    elif [[ $# -eq 1 ]]; then
      # 1 parameter passed
    else
      # 2 or more parameters passed
    fi
}

Dialogue & Discussion