How to include nohup inside a bash script?

烈酒焚心 提交于 2019-11-27 23:00:49

Try putting this at the beginning of your script:

#!/bin/bash

case "$1" in
    -d|--daemon)
        $0 < /dev/null &> /dev/null & disown
        exit 0
        ;;
    *)
        ;;
esac

# do stuff here

If you now start your script with --daemon as an argument, it will restart itself detached from your current shell.

You can still run your script "in the foreground" by starting it without this option.

Create an alias of the same name in your bash (or preferred shell) startup file:

alias mandacalc="nohup mandacalc &"

There is a nice answer here: http://compgroups.net/comp.unix.shell/can-a-script-nohup-itself/498135

#!/bin/bash

### make sure that the script is called with `nohup nice ...`
if [ "$1" != "calling_myself" ]
then
    # this script has *not* been called recursively by itself
    datestamp=$(date +%F | tr -d -)
    nohup_out=nohup-$datestamp.out
    nohup nice "$0" "calling_myself" "$@" > $nohup_out &
    sleep 1
    tail -f $nohup_out
    exit
else
    # this script has been called recursively by itself
    shift # remove the termination condition flag in $1
fi

### the rest of the script goes here
. . . . .

Why don't you just make a script containing nohup ./original_script ?

Just put trap '' HUP on the beggining of your script.

Also if it creates child process someCommand& you will have to change them to nohup someCommand& to work properly... I have been researching this for a long time and only the combination of these two (the trap and nohup) works on my specific script where xterm closes too fast.

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