Have BASH script fork itself into background (BASH)

Sometimes you want a BASH script to be able to fork itself, so that it continues to run in the background, so that it keeps running even if (say) the SSH session is disconnected.

Although you could trigger it manually when calling your script, sometimes you want it to be conditional - if a lock exists you may not want to fork

The mechanism this snippet uses is fairly simple, it checks to see if an environment variable is set, if not, it sets the variable and forks itself into the background, using nohup to ignore any session disconnects

Details

Snippet

# See if the env flag is set
if [ "$FORKED_TO_BG" = "" ]
then
    # Fork self to background
    FORKED_TO_BG=1 nohup $0 $@ 2>&1 >/dev/null
    exit 0
fi

# Otherwise, do stuff
echo "Running"

Usage Example

#!/bin/bash
#
# If you're triggering via SSH, you want to ensure SSH gets a tty
#
# i.e. ssh -t user@box command
#
LOCKFILE="/tmp/lock"

if [ -f $LOCKFILE ]
then
    echo "Lockfile exists, refusing to run"
    exit 1
fi

# See if the env flag is set
if [ "$FORKED_TO_BG" = "" ]
then
    # Fork self to background
    FORKED_TO_BG=1 nohup $0 $@ 2>&1 >/dev/null
    echo "$$ Forked"
    exit 0
fi

# Do stuff
touch $LOCKFILE
echo "$$ Running normally" >> /tmp/out
rm $LOCKFILE