Created
January 22, 2019 12:20
-
-
Save chmduquesne/1950107eb7861af0d872cbcd6d6d6c62 to your computer and use it in GitHub Desktop.
dtach_manager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
[ -n "$DTACH" ] && exit | |
DTACHDIR=$HOME/.dtach | |
[ ! -d "$DTACHDIR" ] && mkdir -p "$DTACHDIR" | |
pick_session(){ | |
[ -n "$(ls -1 $DTACHDIR)" ] && ls -1 $DTACHDIR | pick | |
} | |
get_pid(){ | |
ss --unix --processes --no-header state listening src $DTACHDIR/$1 | | |
awk -F, '{print $2}' | sed 's/pid=//' | |
} | |
session="bash-$(date +%Y-%m-%d@%H:%M:%S)" | |
DTACH=1 dtach -A "$DTACHDIR/$session" -z -e '^b' bash | |
while [ -z "$DTACH" ]; do | |
# No more sessions available, we stop | |
if [ -z "$(ls -1 $DTACHDIR)" ]; then | |
break | |
fi | |
pid=$(get_pid $session) | |
# re-attach at exit | |
if [ -z $pid ]; then | |
session=$(ls -1 $DTACHDIR | head -n1) | |
else | |
read -n1 -s action | |
case $action in | |
s) | |
# switch session | |
session=$(pick_session) || continue | |
;; | |
k) | |
# kill session | |
tokill=$(pick_session) || continue | |
tokill_pid=$(get_pid $tokill) || continue | |
kill $tokill_pid | |
;; | |
a) | |
# abandon session: kill active session and switch | |
tokill_pid=$(get_pid $session) || continue | |
session=$(pick_session) || continue | |
# if we reselect the same session, don't kill it | |
if [ "$tokill_pid" != $(get_pid $session) ]; then | |
kill $tokill_pid | |
fi | |
;; | |
*) | |
# No action, we re-attach to the active session | |
;; | |
esac | |
fi | |
if [ -e "$DTACHDIR/$session" ]; then | |
dtach -a "$DTACHDIR/$session" -z -e '^b' | |
fi | |
done | |
echo "No more sessions - terminating" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment