diff --git a/scripts/tmuxs/helpers.sh b/scripts/tmuxs/helpers.sh new file mode 100644 index 0000000..eb4abb7 --- /dev/null +++ b/scripts/tmuxs/helpers.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +function current_session { + tty=$(tty) + for s in $(tmux list-sessions -F '#{session_name}' 2>/dev/null); do + tmux list-panes -F '#{pane_tty} #{session_name}' -t "$s" + done | grep "$tty" | awk '{print $2}' +} + +function list_sessions { + tmux list-sessions -F "#{session_activity},#{session_id},#{session_name}" \ + | sort -nr | cut -d, -f2,3 | format_session_string +} + +# Given the input "#{session_id},#{session_name}" from tmux ($7,my_session for example) +# will output : : ") +function get_session_name { + sed 's/[[:digit:]]\+\:\s//' +} diff --git a/scripts/tmuxs/kill.sh b/scripts/tmuxs/kill.sh index 672c5af..3c28735 100755 --- a/scripts/tmuxs/kill.sh +++ b/scripts/tmuxs/kill.sh @@ -1,11 +1,12 @@ #!/usr/bin/env bash +BASE_PATH=$(dirname $(readlink -f $BASH_SOURCE)) +source ${BASE_PATH}/helpers.sh -SESSION=$(echo $@ | sed 's/: .*//g') -CURRENT=$(tmux list-sessions -F "#{session_name}" -f "#{session_attached}" | head -n 1) +SESSION=$(echo $@ | get_session_name) # If we are killing the current session. Move to another -if [ "$CURRENT" == "$SESSION" ]; then - NEXT=$(tmux list-sessions -F "#{session_name}" -f "#{==:#{session_attached},0}" | head -n 1) +if [ "$(current_session)" == "$SESSION" ]; then + NEXT=$(list_sessions | grep -v "${SESSION}" | head -n 1 | get_session_name) if [ ! -z "$NEXT" ]; then tmux switch -t "${NEXT}" fi diff --git a/scripts/tmuxs/main.sh b/scripts/tmuxs/main.sh index 26e431c..f10cd4e 100755 --- a/scripts/tmuxs/main.sh +++ b/scripts/tmuxs/main.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash BASE_PATH=$(dirname $(readlink -f $BASH_SOURCE)) +source ${BASE_PATH}/helpers.sh source ${BASE_PATH}/.env # Scripts @@ -9,7 +10,8 @@ KILL_SCRIPT=${BASE_PATH}/kill.sh if [[ $# -eq 1 ]]; then if [[ "$1" == "-a" ]]; then - selected=$($LIST_SESSIONS_SCRIPT | $FZF --bind "ctrl-d:execute(${KILL_SCRIPT} {})+reload(${LIST_SESSIONS_SCRIPT})" --border-label=Session | sed 's/: .*//g') + selected=$($LIST_SESSIONS_SCRIPT | $FZF --bind "ctrl-d:execute(${KILL_SCRIPT} {})+reload(${LIST_SESSIONS_SCRIPT})" \ + --border-label=Session | get_session_name) if [ ! -z "$selected" ]; then ${BASE_PATH}/new.sh $selected fi