
有沒有辦法檢查螢幕會話是否正在 bash 中運行?
例如:
if [screen is running]
then
screen -r #if session is running then resume the session
else
screen "command" #else start a new session
fi
答案1
利用PPID
(Parent PID
) 環境變量,並從
$ ps -fp$PPID
UID PID PPID C STIME TTY TIME CMD
w3 19305 19304 0 00:00 ? 00:00:00 SCREEN
+w3@aardvark:~(0)$
或者,
ps -fp$PPID | head -n 2 | tail -n 1 | egrep -q SCREEN
screen_is_running=$((1 - ${PIPESTATUS[-1]}))
# screen_is_running == 1 for yes, 0 for No, -1 for egrep error
$PPID
當然,如果您已經產生、執行、nohup 或其他操作,並且使您的螢幕不被屏蔽,那麼這將不起作用。
如果是這種情況,您可以使用pgrep
,建立一些pstree
可以egrep
沿著$PPID
鏈返回的東西(當為 1 時停止$PPID
)。
答案2
透過閱讀,man screen
您會發現COMMAND LINE OPTIONS
:
COMMAND-LINE OPTIONS
Screen has the following command-line options:
...snip...
-d -r Reattach a session and if necessary detach it first.
-d -R Reattach a session and if necessary detach or even create it first.
-d -RR Reattach a session and if necessary detach or create it. Use the first session if more than one session is available.
-D -r Reattach a session. If necessary detach and logout remotely first.
-D -R Attach here and now. In detail this means: If a session is running, then reattach. If necessary detach and logout remotely first. If it was not running create it and notify
the user. This is the author's favorite.
-D -RR Attach here and now. Whatever that means, just do it.
Note: It is always a good idea to check the status of your sessions by means of "screen -list".
當然,其中之一可以在沒有變數的情況下完成您想要的操作。