Run bash script in background by default

让人想犯罪 __ 提交于 2021-02-05 07:48:28

问题


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?


回答1:


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.




回答2:


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
...


来源:https://stackoverflow.com/questions/48619765/run-bash-script-in-background-by-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!