How to include nohup inside a bash script?

时光总嘲笑我的痴心妄想 提交于 2019-11-26 20:59:54

问题


I have a large script called mandacalc which I want to always run with the nohup command. If I call it from the command line as:

nohup mandacalc &

everything runs swiftly. But, if I try to include nohup inside my command, so I don't need to type it everytime I execute it, I get an error message.

So far I tried these options:

nohup (
command1
....
commandn
exit 0
)

and also:

nohup bash -c "
command1
....
commandn
exit 0
" # and also with single quotes.

So far I only get error messages complaining about the implementation of the nohup command, or about other quotes used inside the script.

cheers.


回答1:


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.




回答2:


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

alias mandacalc="nohup mandacalc &"



回答3:


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



回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/6168781/how-to-include-nohup-inside-a-bash-script

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