Bash Simple Function


Example

In helloWorld.sh

#!/bin/bash

# Define a function greet
greet ()
{
    echo "Hello World!"
}

# Call the function greet
greet

In running the script, we see our message

$ bash helloWorld.sh
Hello World!

Note that sourcing a file with functions makes them available in your current bash session.

$ source helloWorld.sh   # or, more portably, ". helloWorld.sh"
$ greet
Hello World!

You can export a function in some shells, so that it is exposed to child processes.

bash -c 'greet'  # fails
export -f greet  # export function; note -f
bash -c 'greet'  # success