如何在Bash脚本中使用nohup?

19

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

nohup mandacalc &

一切运行得非常顺利。但是,如果我尝试将nohup包含在我的命令中,以便每次执行时不需要手动输入它,我会收到一个错误消息。

到目前为止,我尝试了以下选项:

nohup (
command1
....
commandn
exit 0
)

并且:

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

到目前为止,我只收到关于nohup命令实现或脚本内使用其他引号的错误消息。

谢谢。


你需要给 nohup 命令提供完整路径吗?which nohup - wilbbe01
6个回答

26

尝试将以下代码放在你的脚本开头:

#!/bin/bash

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

# do stuff here

如果你现在使用--daemon作为参数启动你的脚本,它将会在后台自动重启而不受当前shell的影响。

如果不使用这个选项,你仍然可以在前台运行你的脚本。


这不仅限于脚本没有参数的情况吗? - Yan Foto
@YanFoto 你是正确的。为了传递所有参数,该行应更改为 $0 "$@" < /dev/null &> /dev/null & disown - mattalxndr
1
@mattalxndr:不完全是这样:首先,您应该解析参数并取出“--daemon”,否则您将陷入分叉循环。 - Olivier Dulac
你应该这样做:for arg in "$@"; do if [ "$arg" = "-d" ] || [ "$arg" = "-daemon" ]; then start_as_daemon="true" ; else other_args+=( "$arg" ) ; fi ; if [ "$start_as_daemon" = "true" ]; then $0 "${other_args[@]}" </dev/null >&/dev/null & disown ; exit 0 ; fi - Olivier Dulac

6
在您的bash(或首选shell)启动文件中创建相同名称的别名:
alias mandacalc="nohup mandacalc &"

6

只需在脚本开头添加 trap '' HUP

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


这是唯一一个对我有效的。谢谢你,亲切的陌生人! - Iuliana Cosmina

4
为什么不直接编写一个脚本包含 nohup ./original_script 呢?

4

这里有一个不错的答案: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
. . . . .

-1

处理这个问题的最佳方式是使用$()

nohup $( command1, command2 ...) &

nohup 希望只有一个命令,这样您就可以使用一个 nohup 执行多个命令。


1
我认为这个不起作用。$() 语法将运行一些命令并在调用 nohup 之前包含它们的输出。 - Dan R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接