默认情况下在后台运行bash脚本

时间:2018-02-05 09:54:10

标签: bash background-process

我知道我可以使用bash script.sh & disown或者使用nohup在后​​台运行我的bash脚本。但是,我希望默认情况下在后台运行我的脚本,因此当我运行bash script.sh或使其成为可执行文件后,通过运行./script.sh它默认情况下应该在后台运行。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:3)

独立解决方案:

#!/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

if语句检查是否已传递-n标志。如果没有,它会调用自己nohup(取消关联主叫终端,因此关闭它不会关闭脚本)和&(将进程置于后台并返回提示)。然后父母退出以退出后台版本以运行。使用-n标志显式调用后台版本,因此不会导致无限循环(这是调试的地狱!)。

for循环只是一个例子。使用tail -f nohup.out查看脚本的进度。

请注意,我将此答案与thisthis拼凑在一起,但两者都不够简洁或完整,无法复制。

答案 1 :(得分:1)

只需编写一个使用nohup actualScript.sh &调用实际脚本的包装器。

包装器脚本wrapper.sh

#! /bin/bash

nohup ./actualScript.sh &

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

答案 2 :(得分:0)

除了 Heath Raftery 的 answer 之外,对我有用的是他建议的变体,例如:

if [[ "$1" != "-n" ]]; then
    $0 -n & disown
    exit $?
fi
相关问题