From c13cbee080ae3667f48e36141f6f4c2811c2ac9f Mon Sep 17 00:00:00 2001 From: TBS093A Date: Thu, 4 May 2023 18:35:07 +0200 Subject: [PATCH] feat: add tmux.session.sh for save & restore sessions + add alias to this script in .zshrc file --- make.symlinks.sh | 1 + tmux.config/tmux.session.sh | 70 +++++++++++++++++++++++++++++++++++++ zsh.config/.zshrc | 2 ++ 3 files changed, 73 insertions(+) create mode 100755 tmux.config/tmux.session.sh diff --git a/make.symlinks.sh b/make.symlinks.sh index 308d780..c1ec35e 100755 --- a/make.symlinks.sh +++ b/make.symlinks.sh @@ -17,3 +17,4 @@ ln -s $(pwd)/sshd.ssh.config/sshd_config /etc/ssh/sshd_config ln -s $(pwd)/vim.config/init.vim ~/.config/nvim/init.vim + diff --git a/tmux.config/tmux.session.sh b/tmux.config/tmux.session.sh new file mode 100755 index 0000000..1ecc26d --- /dev/null +++ b/tmux.config/tmux.session.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# Save and restore the state of tmux sessions and windows. +# TODO: persist and restore the state & position of panes. + +# source: https://superuser.com/questions/440015/restore-tmux-session-after-reboot +# github: https://raw.githubusercontent.com/mislav/dotfiles/d2af5900fce38238d1202aa43e7332b20add6205/bin/tmux-session + +# you can map `tmux-session.sh save` on cronjob - it's really helpful because +# sometimes you can forget about save session manually +# +# usage: +# +# tmux-session.sh save (for session save) +# +# tmux-session restore (for restore all sessions) + +set -e + +dump() { + local d=$'\t' + tmux list-windows -a -F "#S${d}#W${d}#{pane_current_path}" +} + +save() { + dump > ~/.tmux-session +} + +terminal_size() { + stty size 2>/dev/null | awk '{ printf "-x%d -y%d", $2, $1 }' +} + +session_exists() { + tmux has-session -t "$1" 2>/dev/null +} + +add_window() { + tmux new-window -d -t "$1:" -n "$2" -c "$3" +} + +new_session() { + cd "$3" && + tmux new-session -d -s "$1" -n "$2" $4 +} + +restore() { + tmux start-server + local count=0 + local dimensions="$(terminal_size)" + + while IFS=$'\t' read session_name window_name dir; do + if [[ -d "$dir" && $window_name != "log" && $window_name != "man" ]]; then + if session_exists "$session_name"; then + add_window "$session_name" "$window_name" "$dir" + else + new_session "$session_name" "$window_name" "$dir" "$dimensions" + count=$(( count + 1 )) + fi + fi + done < ~/.tmux-session + echo "restored $count sessions" +} + +case "$1" in +save | restore ) + $1 + ;; +* ) + echo "valid commands: save, restore" >&2 + exit 1 +esac diff --git a/zsh.config/.zshrc b/zsh.config/.zshrc index 2a7ad9b..994fc5f 100644 --- a/zsh.config/.zshrc +++ b/zsh.config/.zshrc @@ -102,3 +102,5 @@ source $ZSH/oh-my-zsh.sh # alias ohmyzsh="mate ~/.oh-my-zsh" [ -f ~/.fzf.zsh ] && source ~/.fzf.zsh + +alias tmux-session=/root/linux.config/tmux.config/tmux.session.sh