How to run a function in background?

You can use a shell function pretty much anywhere you can use a program. Just remember that shell functions don't exist outside the scope in which they were created.

#!/bin/bash
#
f() {
    sleep 1
    echo "f: Hello from f() with args($*)" >&2
    sleep 1
    echo "f: Goodbye from f()" >&2
}

echo "Running f() in the foreground" >&2
f one

echo "Running f() in the background" >&2
f two &

echo "Just waiting" >&2
wait

echo "All done"
exit 0

You run them in the background as in any other shell command or script with a & at the end.

Bash and similar shells also allow you to combine commands with ( and ) such as:

(command1; command2) &

Tags:

Function