Search code examples
bashbackground-process

Run bash script in background by default


I know I can run my bash script in the background by using bash script.sh & disown or alternatively, by using nohup. However, I want to run my script in the background by default, so when I run bash script.sh or after making it executable, by running ./script.sh it should run in the background by default. How can I achieve this?


Solution

  • Self-contained solution:

    #!/bin/sh
    
    # Re-spawn as a background process, if we haven't already.
    if [[ "$1" != "-n" ]]; then
        nohup "$0" -n &
        exit $?
    fi
    
    # Rest of the script follows. This is just an example.
    for i in {0..10}; do
        sleep 2
        echo $i
    done
    

    The if statement checks if the -n flag has been passed. If not, it calls itself with nohup (to disassociate the calling terminal so closing it doesn't close the script) and & (to put the process in the background and return to the prompt). The parent then exits to leave the background version to run. The background version is explicitly called with the -n flag, so wont cause an infinite loop (which is hell to debug!).

    The for loop is just an example. Use tail -f nohup.out to see the script's progress.

    Note that I pieced this answer together with this and this but neither were succinct or complete enough to be a duplicate.