16

我有一个名为mandacalc的大型脚本,我想始终使用nohup命令运行它。如果我从命令行调用它:

nohup mandacalc &

一切都运行得很快。但是,如果我尝试在我的命令中包含nohup,这样我就不需要在每次执行它时都输入它,我会收到一条错误消息。

到目前为止,我尝试了这些选项:

nohup (
command1
....
commandn
exit 0
)

并且:

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

到目前为止,我只收到抱怨nohup命令的实施或脚本中使用的其他引号的错误消息。

干杯。

4

5 回答 5

23

尝试将其放在脚本的开头:

#!/bin/bash

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

# do stuff here

如果您现在将脚本--daemon作为参数启动,它将重新启动,并与您当前的 shell 分离。

您仍然可以通过在不使用此选项的情况下启动脚本来“在前台”运行脚本。

于 2011-05-29T16:47:20.730 回答
5

在 bash(或首选 shell)启动文件中创建同名别名:

alias mandacalc="nohup mandacalc &"
于 2011-05-29T17:05:59.410 回答
5

只需放在trap '' HUP脚本的开头即可。

此外,如果它创建子进程someCommand&,您将不得不将它们更改nohup someCommand&为正常工作......我已经研究了很长时间,只有这两者(陷阱和 nohup)的组合适用于我的 xterm 关闭的特定脚本快速地。

于 2013-06-11T05:29:11.303 回答
3

你为什么不制作一个包含 的脚本nohup ./original_script

于 2011-05-29T16:18:59.323 回答
3

这里有一个很好的答案: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
. . . . .
于 2015-07-04T12:41:54.333 回答