A function is a set of commands with a name. They are useful when the same series of commands needs to run multiple places in your script. And can also be used to provide a better structure for your scripts.

There are two ways to specify a function:

function function_name() {
  commands
}

Or

function_name() {
  commands
}

Arguments works the same way they do for scripts see Dec 2 for details.

#!/bin/bash
greeting="Hello"

function hello() {
  local name=$1
  echo "$greeting $name"
}

hello Bob

Variables are global by default. To declare a variable that only exists inside the function you can use the local keyword.

Beware that a functions must be defined (earlier in the script) before it can be invoked.

You can specify an “exit-code” for the function by ending it with a return statement.

#!/bin/bash
function meaning() {
  return 42
}
meaning
echo "Function exit code: $?"

If you want your function to output some text then you can use the echo command and assign the output of a function to a variable.

#!/bin/bash
greeting="Hello"

function hello() {
  local name=$1
  echo "$greeting $name"
}

output=$(hello Bob)
echo "Output from function: $output"