如何在Bash中检测tmux会话是否存在及是否已连接?
Optimized tmux Session Creation & Connection Script
Your core requirement is to safely create a tmux session only if it doesn't exist, and attach to it only when you're not already inside a tmux session. Here's a clean, reliable approach that avoids parsing tmux ls output (which can be fragile) and uses tmux's built-in tools for better robustness.
Key Checks to Use
Instead of grepping tmux ls, rely on these more reliable methods:
- Check if a session exists: Use
tmux has-session -t <session-name> 2>/dev/null. This command exits with a status code of 0 if the session exists, and non-zero otherwise. Redirecting stderr to/dev/nullsuppresses the error message when the session isn't found. - Check if you're already in tmux: Verify if the
TMUXenvironment variable is set. If it's empty, you're outside a tmux session; if it's present, you're already attached to one.
Full Script Implementation
Here's a complete script that meets all your requirements:
#!/bin/bash # Define your session name SESSION_NAME="ax" # Step 1: Create the session only if it doesn't exist if ! tmux has-session -t "$SESSION_NAME" 2>/dev/null; then # Create the initial session with a window named 'ui' (detached mode) tmux new-session -s "$SESSION_NAME" -n ui -d # Add additional windows here (only runs once when the session is first created) tmux new-window -t "$SESSION_NAME" -n backend tmux new-window -t "$SESSION_NAME" -n logs # Optional: Set the default window to 'ui' when attaching tmux select-window -t "$SESSION_NAME:ui" fi # Step 2: Attach to the session only if not already in tmux if [ -z "$TMUX" ]; then tmux attach-session -t "$SESSION_NAME" else echo "Already inside a tmux session. To switch to $SESSION_NAME, use: tmux switch-client -t $SESSION_NAME" fi
How It Works
- Session Creation: The
if ! tmux has-sessionblock ensures we only run the session setup (initial window + additional windows) once, when the session is first created. This prevents duplicate windows if the script is run multiple times. - Attachment Logic: The
[ -z "$TMUX" ]check ensures we only attach to the session if we're not already inside tmux. If we are in tmux, we print a helpful tip for switching sessions instead.
Extra Tips
- Switching Sessions: If you're already in tmux and want to switch to your
axsession, usetmux switch-client -t axinstead of attaching again. - Idempotent Setup: All the commands inside the session creation block run only when the session doesn't exist — exactly what we want to avoid duplicate windows or sessions.
- Clean Output: Redirecting stderr in
tmux has-sessionkeeps the script quiet when the session doesn't exist, avoiding unnecessary error messages.
内容的提问来源于stack exchange,提问作者GibboK
相关产品推荐
相关产品推荐

