Skip to content

Instantly share code, notes, and snippets.

@mdeweerd
Last active January 28, 2025 00:02
Show Gist options
  • Save mdeweerd/e6d3a393e24cbf2a4373df1ffb6a7479 to your computer and use it in GitHub Desktop.
Save mdeweerd/e6d3a393e24cbf2a4373df1ffb6a7479 to your computer and use it in GitHub Desktop.
Interactively select a GNU Screen session
#!/bin/bash
#
# Shell function to list the screen sessions on a machine
# and let the user select one from the list using up-down
# arrows.
#
# Add this to your `.bashrc` file or to your `.bashrc.d` directory
# where you should make it executable to be automatically
# sourced in some default `.bashrc` scripts.
selected_session=""
# Function to list all screen sessions with full details
list_sessions() {
screen -ls | grep -P '^\t'
}
# Function to select a session using arrow keys
select_session() {
local selected=0
local sessions
# Convert the output to an array using mapfile
mapfile -t sessions < <(list_sessions)
while true; do
clear
echo "Select a screen session '$selected':"
for i in "${!sessions[@]}"; do
if [ "$i" -eq "$selected" ]; then
echo "> ${sessions[$i]}"
else
echo " ${sessions[$i]}"
fi
done
read -rsn1 key
case $key in
$'\x1b') # Escape sequence for arrow keys
read -rsn2 key
case $key in
'[A') # Up arrow
((selected--))
if [ $selected -lt 0 ]; then
selected=$(( ${#sessions[@]} - 1 ))
fi
;;
'[B') # Down arrow
((selected++))
if [ $selected -ge ${#sessions[@]} ]; then
selected=2
fi
;;
esac
;;
"") # Enter key
selected_session="${sessions[$selected]}"
return 0
;;
esac
done
}
# Function to extract the session ID from the selected line
extract_session_id() {
local line="$1"
echo "$line" | grep -oP '\d+\.[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+'
}
# Function to switch to a selected screen session
sel_screen() {
select_session
if [ -n "$selected_session" ]; then
local session_id
session_id=$(extract_session_id "$selected_session")
# Attach to the selected session
screen -dr "$session_id"
#screen -d -r -x "$session_id"
#screen -xr "$session_id"
#screen -d -RR "$session_id"
else
echo "No session selected."
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment