有没有办法检查屏幕会话是否在 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
当然,如果您已经生成、执行、nohup 或执行了其他操作,并且没有使屏幕显示,那么这将不起作用$PPID
。
如果是这种情况,您可以用 、 构建一些东西,pgrep
可以沿着链条往回走(当为 1 时停止)。pstree
egrep
$PPID
$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".
当然,其中一个可以在没有变量的情况下完成你想要做的事情。