tmux-SESSION.sh 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env bash
  2. set -euo pipefail # bash strict mode
  3. # Save and restore the state of tmux sessions and windows.
  4. # TODO: persist and restore the state & position of panes.
  5. set -e
  6. dump() {
  7. local d=$'\t'
  8. tmux list-windows -a -F "#S${d}#W${d}#{pane_current_path}"
  9. }
  10. save() {
  11. dump > ~/.tmux-session
  12. }
  13. terminal_size() {
  14. stty size 2>/dev/null | awk '{ printf "-x%d -y%d", $2, $1 }'
  15. }
  16. session_exists() {
  17. tmux has-session -t "$1" 2>/dev/null
  18. }
  19. add_window() {
  20. tmux new-window -d -t "$1:" -n "$2" -c "$3"
  21. }
  22. new_session() {
  23. cd "$3" &&
  24. tmux new-session -d -s "$1" -n "$2" $4
  25. }
  26. restore() {
  27. tmux start-server
  28. local count=0
  29. local dimensions="$(terminal_size)"
  30. while IFS=$'\t' read session_name window_name dir; do
  31. if [[ -d "$dir" && $window_name != "log" && $window_name != "man" ]]; then
  32. if session_exists "$session_name"; then
  33. add_window "$session_name" "$window_name" "$dir"
  34. else
  35. new_session "$session_name" "$window_name" "$dir" "$dimensions"
  36. count=$(( count + 1 ))
  37. fi
  38. fi
  39. done < ~/.tmux-session
  40. echo "restored $count sessions"
  41. }
  42. case "$1" in
  43. save | restore )
  44. $1
  45. ;;
  46. * )
  47. echo "valid commands: save, restore" >&2
  48. exit 1
  49. esac