Have BASH script fork itself into background



Published: 2020-08-10 13:42:47 +0000
Categories: BASH,

Language

BASH

Description

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

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

License

BSD-3-Clause

Keywords

HUP, fork, background, nohup,

Latest Posts


Copyright © 2020 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk and http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion