Linux – How to Check if Running Inside a GNU Screen

gnu-screenlinux

The "screen" refers to a program mentioned in How to reconnect to a disconnected ssh session . That is a good facility.

But there is a question I'd really like to know. How do I know whether I'm running inside a "screen"? The difference is:

  • If yes, I know I can safely close current terminal window, e.g., close a PuTTY window, without losing my shell(Bash etc) session.
  • If no, I know I have to take care of any pending works before I close the terminal window.

Better, I'd like this status to be displayed in PS1 prompt so that I can see it any time automatically.

Best Answer

(Stolen from "How can I tell whether I'm in a screen?" over on StackOverflow and authored by user jho. P.S. You can't vote for a duplicate across StackExchange sites.)

Check $STY. If it's null, you're on a "real" terminal. If it contains anything, it's the name of the screen you're in.

If you are not in screen:

eric@dev ~ $ echo $STY
eric@dev ~ $ 

If you are in screen:

eric@dev ~ $ echo $STY
2026.pts-0.ip-10-0-1-71

If you use tmux instead of screen, also check $TMUX. To add this to your prompt, add the following to your ~/.bashrc:

if [ -n "$STY" ]; then export PS1="(screen) $PS1"; fi
if [ -n "$TMUX" ]; then export PS1="(tmux) $PS1"; fi
Related Topic