スクリーンセッションが実行中かどうかを確認するにはどうすればいいですか?

スクリーンセッションが実行中かどうかを確認するにはどうすればいいですか?

bash で screen セッションが実行されているかどうかを確認する方法はありますか?
例:

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

もちろん、spawn、exec、nohup などを実行して$PPIDnot SCREEN にした場合、これは機能しません。

その場合は、、を使用して、チェーンをたどることができるものを構築できますpgrep(がpstree1のときに停止します)。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".

確かに、これらのいずれかが変数なしで必要なことを実行します。

関連情報