Skip to content

Instantly share code, notes, and snippets.

@henri
Forked from thunderpoot/ghostbuster
Created February 14, 2024 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henri/7e0390ff154df4f8993ea2f1903ac2f1 to your computer and use it in GitHub Desktop.
Save henri/7e0390ff154df4f8993ea2f1903ac2f1 to your computer and use it in GitHub Desktop.
Mosh: You have N detached Mosh sessions on this server
#!/bin/bash
# You know that really annoying message that pops up...
# Mosh: You have 3 detached Mosh sessions on this server, with PIDs:
# - mosh [2294539]
# - mosh [1874313]
# - mosh [2294805]
# I often find myself copying this list of PIDs in order to kill them manually
# ... so this script was born. Maybe others will find it useful.
declare -A colours
colours[green]="\e[32;1m"
colours[blue]="\e[34;1m"
colours[red]="\e[31;1m"
colours[reset]="\e[0m"
printc()
{
local colour=${colours[$1]} message=$2
printf "${colour}${message}${colours[reset]}"
}
printf "Please paste the list of detached Mosh sessions (^D ends input)\n"
printf "===============================================================\n"
# Read multi-line input from user
input_list=$(cat)
# Extract PIDs from the pasted list
pids=$(echo "$input_list" | grep -oP '\[\K[0-9]+')
# Check if any PIDs were found
if [ -z "$pids" ]; then
printc blue "No PIDs found in the input.\n"
else
# Confirm with the user before killing the sessions
printc blue "The following PIDs will be terminated:\n"
echo "$pids" | awk '{print " - "$1}'
printc blue "Do you want to proceed? [y/N] "
read confirmation
if [[ "$confirmation" =~ ^[yY](es)?|YES$ ]]; then
# Kill each PID
for pid in $pids; do
printc blue "Killing Mosh session with PID $pid\n"
kill $pid
done
printc green "Done.\n"
else
printc red "Operation cancelled.\n"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment