Summary
Learn how to enhance your ZSH prompt with a color-coded indicator showing the number of displays attaching the current GNU Screen sessions, helping you maintain awareness of your terminal multiplexer state.
Introduction
In a setting where more than one person has access to GNU Screen sessions, I often found myself wondering how many terminals were currently attached to the current session. This becomes particularly important when you need to ensure that no conflicting tasks are running in the same session.
The Solution
We'll implement a prompt modification that shows the number of attached displays, color-coded for quick visual feedback:
- Green for single attachment (ideal state)
- Red for multiple attachments (potential conflict state)
Implementation
The Screen Counter Script
First, create bin/screen-user-count
:
#!/bin/bash screen -ls "$STY" | while read scr do if [[ "$scr" =~ ^[0-9]+\. ]]; then pid=${scr%%.*} cnt=$(ls -l /proc/$pid/fd/ | grep pts | wc -l) echo "$scr [$cnt]" else echo "$scr" fi done
This is a slightly modified version of a solution on StackExchange,
which works nicely. I modified it to use the environment variable
$STY
, so that if called from within a screen session the query is
limit to the currently attached session. This ensures that in our
scenario we will always get exactly one result.
ZSH Configuration
Add to your ~/.zshrc
:
suc() { local count=$(bin/screen-user-count | grep Attached | awk -F'[][]' '{print $2}') if [[ $count -eq 1 ]]; then echo "%F{green}${count}%f" else echo "%F{red}${count}%f" fi } setopt PROMPT_SUBST precmd() { PROMPT="%m %~ $(suc) %# " }
How It Works
- The
screen-user-count
script checks /proc filesystem for terminal attachments suc()
function extracts the count and applies color formattingprecmd()
integrates the count into your prompt
Bonus
As a last line in our ~/.zshrc
we have:
[ -z "$STY" ] && screen -xR && logout
The last line goes beyond the topic of this post. First it guards against running from within a screen session, so the line is only executed upon login. Then it immediately auto-attaches a previous session or creates one, if there is none. Finally after detaching the session it immediately performes a logout. This ensures that a user logged in to the machine will allways be in a possibly shared screen session.
If you liked this post, please consider supporting our Free and Open Source software work – you can sponsor us on Github and Patreon or star our FLOSS repositories.