SSH into a tmux session on a server.
When working on remote servers, losing SSH connections can be frustrating and disrupt your workflow. Here's a simple bash function that automatically starts or reattaches to a tmux session when connecting to a server, while also syncing your local tmux configuration.
Add this to your ~/.bashrc or ~/.zshrc, then simply use ssht <hostname>
to connect. Your session will persist even if your connection drops.
function ssht() {
local tmux_config_path="${HOME}/.config/tmux/tmux-server.conf"
local remote_tmux_config_path="~/.tmux.conf"
# copy the local tmux config file to the remote server
if [[ -f "$tmux_config_path" ]]; then
scp "$tmux_config_path" "$1:$remote_tmux_config_path"
ssh -t "$@" "chmod 750 $remote_tmux_config_path"
else
echo "Local tmux config file not found at ${tmux_config_path}"
fi
# set the window name to the host name
if [ -n "$TMUX" ]; then
local host=$(echo "$@" | awk '{print $NF}' | sed 's/@.*//')
tmux rename-window "$host"
fi
# ssh into the remote server and start tmux
ssh -t "$@" "tmux attach || tmux new-session"
}