检查 bash 脚本是否是从 shell 或其他脚本/应用程序调用的 [英] Check if bash script was invoked from a shell or another script/application

查看:32
本文介绍了检查 bash 脚本是否是从 shell 或其他脚本/应用程序调用的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 bash 脚本来将另一个命令的输出重定向到正确的位置.基本上,当从 shell/命令行调用脚本时,我想将输出发送到 STDOUT.但是,当 bash 脚本是从某个其他应用程序(例如另一个 bash 脚本、某个应用程序,或者在我的例子中从我的 Awesome Window Manager 中的 awesome-prompt 插件)执行时,我想将输出重定向到其他地方.

I am writing a bash script to redirect output from another command to the proper location. Basically, when the script is invoked from a shell/commandline I want to send the output to STDOUT. But, when the bash script is executed from some other application (e.g. another bash script, some application, or in my case from the awesome-prompt plugin in my Awesome Window Manager) I want to redirect the output somewhere else.

在 bash 中有什么方法可以查看脚本是如何被调用的吗?

Is there any way in bash to see how a script was invoked?

推荐答案

试试这个:

ps -o stat= -p $PPID

如果结果包含s"(小写),则它要么是从命令行运行的,要么是从脚本内部运行的.区分这两者:

If the result contains "s" (lowercase) it was either run from the command line or backgrounded from within a script. To tell those two apart:

ps -o stat= -p $$

如果没有背景,将包含一个+".

will contain a "+" if it was not backgrounded.

这是一张表格:

Run          $$    $PPID
CL           S+    Ss
CL&          S     Ss+
Script       S+    S+
Script&      S     S
Script(&)    S     Ss
Script&(&)   S     NULL

其中 (&) 表示子脚本是背景的,并且 &意味着运行它的父脚本(这是脚本"所指的)是后台的.CL 表示命令行.NULL 表示 ps 输出一个空值,并且 $PPID 为1".

Where (&) means the child script was backgrounded and & means the parent script (which is what "Script" refers to) that ran it was backgrounded. CL means command line. NULL means that ps output a null and that $PPID is "1".

来自man ps:

   s    is a session leader
   +    is in the foreground process group

应该注意的是,这个答案是基于 GNU ps,但是 BSD(包括 OS X)的手册页表明了类似的功能.GNU ps 是一个混合体,其中包括 BSD 功能.

It should be noted that this answer is based on GNU ps, but the man pages for BSD (including OS X) indicate similar functionality. And GNU ps is a hybrid that includes BSD functionality, among others.

这篇关于检查 bash 脚本是否是从 shell 或其他脚本/应用程序调用的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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