在后台运行当前bash脚本 [英] Run current bash script in background

查看:118
本文介绍了在后台运行当前bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我添加&放大器;字符开始我的过程中研究背景,为例:

 用户@电脑:〜$ my_script&安培;

但我怎么可以让它在后台没有与&人物?

 #!/斌/庆典#What可以加我这里隐藏当前进程($$)并释放焦点?START_SERVER()
{
    #我的剧本在这里与无限循环......
}

谢谢你们。


解决方案

 #!/斌/庆典如果[$ 1=--nodaemon]!]然后
    ($ 0--nodaemon$ @<的/ dev / null的&安培;>的/ dev / null的&安培;)
其他
    转移
科幻#...脚本休息

这样做是什么检查,看看它的第一个参数是--nodaemon,如果是本身($ 0)与后台脱火参数--nodaemon,which'll prevent它试图重新背景本身在一种无限循环的。

注意,把这个作为第一件事就是脚本将使它的总是的在后台运行本身。如果只需要放到特定条件下的背景(例如,当带参数运行开始),你就必须做出相应的调整这一点。也许是这样的:

 #!/斌/庆典START_SERVER()
{
    #我的剧本在这里与无限循环......
}如果[$ 1=开始]];然后
    ($ 0启动nodaemon<的/ dev / null的&安培;>的/ dev / null的&安培;)
ELIF [$ 1=启动nodaemon]];然后
    START_SERVER
ELIF#.....

Usually I add "&" character to start my process in backgroud, exemple :

user@pc:~$ my_script &

But how can I make it in background without "&" character ?

#!/bin/bash

#What can I add here to hide current process ($$) and to release focus ?

start_server()
{   
    #my script here with infinite loop ...
}

Thanks guys.

解决方案

#!/bin/bash

if [[ "$1" != "--nodaemon" ]]; then
    ( "$0" --nodaemon "$@" </dev/null &>/dev/null & )
else
    shift
fi

#...rest of script

What this does is check to see if its first argument is "--nodaemon", and if so fire itself ("$0") off in the background with the argument "--nodaemon", which'll prevent it from trying to re-background itself in a sort of infinite loop.

Note that putting this as the first thing in the script will make it always run itself in the background. If it only needs to drop into the background under certain conditions (e.g. when run with the argument "start"), you'd have to adjust this accordingly. Maybe something like this:

#!/bin/bash

start_server()
{   
    #my script here with infinite loop ...
}

if [[ "$1" = "start" ]]; then
    ( "$0" start-nodaemon </dev/null &>/dev/null & )
elif [[ "$1" = "start-nodaemon" ]]; then
    start_server
elif #.....

这篇关于在后台运行当前bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆