Bash
如何檢查 bash 腳本是否由 GUI 中的“在終端中執行”啟動?
我執行 bash 腳本。我想從終端和使用“在終端中執行”的 GUI 執行它們,並在執行 interactive 後離開
bash
。在這裡簡單地解釋一下輸出:添加read -rn1
。問題 X:我想要一個“乾淨”的解決方案,如果腳本從終端執行並且如果從 GUI 執行
,我可以在最後使用帶有 bash 的相同終端來關閉它。
exit
我可以添加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+
.
我假設您的 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"
根據您的評論,差異是由於添加了
s
:s 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