如何检查 bash 脚本是否是由 GUI 中的“在终端中运行”启动的?

如何检查 bash 脚本是否是由 GUI 中的“在终端中运行”启动的?

我运行 bash 脚本。我想从终端运行它们,并从 GUI 中使用“在终端中运行”运行它们,并在运行交互式后离开bash这里解释了简单地查看输出: 添加read -rn1

问题X
我想要一个“干净”的解决方案,在最后与 bash 具有相同的终端,exit如果脚本从终端运行并且从 GUI 运行,我可以用一个终端关闭。我可以添加bash -i,但如果从终端运行,则需要两个exit才能关闭终端。exec bash -i结果相同。

脚本中有没有办法检查它是否是通过“在终端中运行”从 GUI 启动的?

每条评论添加 1 条:

ps aux | grep aaaa # while script started from GUI was running
mint       53293  0.1  0.0  11216  3356 pts/3    Ss+  21:58   0:00 /bin/bash /home/mint/aaaaa.sh

注意到与从终端启动的区别是Ss+代替S+

答案1

我假设你的 bash 脚本被命名为/path/to/mybashscript.sh

用于ps查找mybashscript.sh$0如果在脚本内运行);包括state/stat用于标识特定状态的列:

ps --sort +pid -eo pid,stat,command | grep "$0" | head -1 | awk '{print $2}' | grep "s"

或另一种过滤行的方法grep

ps -eo pid,stat,command | grep "$0" | grep -v grep | awk '{print $2}' | grep "s"

从您的评论来看,差异是由于添加了ss is a session leader对于 GUI 方式,Ubuntu 没有那种从文件管理器启动脚本进行检查的方式。

man ps,状态代码如下:

PROCESS STATE CODES
   Here are the different values that the s, stat and state output specifiers (header "STAT" or "S") will display
   to describe the state of a process:

           D    uninterruptible sleep (usually IO)
           I    Idle kernel thread
           R    running or runnable (on run queue)
           S    interruptible sleep (waiting for an event to complete)
           T    stopped by job control signal
           t    stopped by debugger during the tracing
           W    paging (not valid since the 2.6.xx kernel)
           X    dead (should never be seen)
           Z    defunct ("zombie") process, terminated but not reaped by its parent

   For BSD formats and when the stat keyword is used, additional characters may be displayed:

           <    high-priority (not nice to other users)
           N    low-priority (nice to other users)
           L    has pages locked into memory (for real-time and custom IO)
           s    is a session leader
           l    is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)
           +    is in the foreground process group

相关内容