1

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?

3 Answers3

4

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.

Heath Raftery
  • 3,643
  • 17
  • 34
1

Simply write a wrapper that calls your actual script with nohup actualScript.sh &.

Wrapper script wrapper.sh

#! /bin/bash

nohup ./actualScript.sh &

Actual script in actualScript.sh

#! /bin/bash

for i in {0..10}
do
    sleep 10  #script is running, test with ps -eaf|grep actualScript
    echo $i 
done

tail -f 10 nohup.out

0
1
2
3
4
...
jschnasse
  • 8,526
  • 6
  • 32
  • 72
0

Adding to Heath Raftery's answer, what worked for me is a variation of what he suggested such as this:

if [[ "$1" != "-n" ]]; then
    $0 -n & disown
    exit $?
fi
KostasVlachos
  • 121
  • 1
  • 5