Improve tmux with a simple bash function

A better way to manage tmux sessions

Are you tired of juggling multiple terminal windows and tabs just to keep your work organized? Enter tmux, a powerful terminal multiplexer that can revolutionize the way you work in the command line.

To make the most of tmux, consider integrating it into your workflow with a simple yet effective script like the one below:

# file -> .zshrc
function tnew() {
    local parent_name="$(basename "$(dirname "$(pwd)")"| tr -d "[:space:]-")"
    local current_name="$(basename "$(pwd)" | tr -d "[:space:]-")"
    local session_name="${parent_name}_${current_name}"

    if tmux has-session -t "$session_name" 2>/dev/null; then
        tmux attach-session -t "$session_name"
    else
        tmux new-session -s "$session_name"
    fi
}

alias tm='tnew'

Let’s break down what this script does:

  • It defines a function tnew() which creates a new tmux session based on the current directory name. This ensures that each project or task you’re working on gets its own dedicated tmux session.

  • The session_name is constructed using the names of the parent and current directories, removing any spaces or hyphens. This helps maintain a clean and consistent naming convention for your tmux sessions.

  • If a session with the same name already exists, the script attaches to it. Otherwise, it creates a new session.

To use this script, simply add it to your shell configuration file (e.g., .bashrc, .zshrc) and reload your shell. Now, instead of manually managing tmux sessions, you can simply type tm in your terminal to create or attach to a session based on your current directory.

With this streamlined workflow, you can say goodbye to terminal clutter and focus on what really matters – getting things done. Give it a try and experience the power of tmux sessions firsthand!


Original post: improve-tmux-with-bash-function on hyperoot.dev.


Connect with me on social media:

Got feedback or questions? Feel free to leave a comment below or reach out to me on my personal site. Your thoughts are valuable!