可以检查它是否在调用时后台运行的 Shell 脚本 [英] Shell Script That Can Check if it Was Backgrounded at Invocation

查看:25
本文介绍了可以检查它是否在调用时后台运行的 Shell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个依赖于其他服务器响应的脚本(使用 wget 提取数据),我希望它毫无疑问地始终在后台运行.我知道一种解决方案是编写一个包装脚本,该脚本将使用&"来调用我的脚本附加,但我想避免这种混乱.

I have written a script that relies on other server responses (uses wget to pull data), and I want it to always be run in the background unquestionably. I know one solution is to just write a wrapper script that will call my script with an '&' appended, but I want to avoid that clutter.

bash(或 zsh)脚本有没有办法确定它是否是用 ./foo.sh& 调用的,如果不是,退出并重新启动?

Is there a way for a bash (or zsh) script to determine if it was called with say ./foo.sh&, and if not, exit and re-launch itself as such?

谢谢大家!

推荐答案

我不知道怎么做,但是你可以在父脚本中设置变量并在子脚本中检查它:

I do not know, how to do this, but you may set variable in parent script and check for it in child:

if [[ -z "$_BACKGROUNDED" ]] ; then
    _BACKGROUNDED=1 exec "$0" "$@" & exit
fi
# Put code here

适用于 bash 和 zsh.

Works both in bash and zsh.

这篇关于可以检查它是否在调用时后台运行的 Shell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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