Table of Contents
A small shell function to connect to a remote Emacs via SSH. It:
- reconnects repeatedly on failure
- allows normal exit
- uses exponential backoff when the network is poor (delay grows up to 30s)
Features
- Continuous reconnect loop.
- Clean exit on normal termination.
- Exponential backoff on errors, capped at 30s.
- Uses
sshwithServerAliveIntervalandServerAliveCountMaxto improve connection stability. - Calls
emacsclient -t -a '' -s serveron the remote host.
Script
Place this function in your shell profile (for example,
~/.bashrcor~/.zshrc).Call it as
emacsclient-remote [user@host]. The default host iswd@nixos-nuc.function emacsclient-remote() { local host="${1:-wd@nixos-nuc}" local delay=2 trap "echo '[INFO] stopped'; return" INT while true; do echo "[INFO] connecting to $host at $(date)" ssh \ -o ServerAliveInterval=30 \ -o ServerAliveCountMax=3 \ -t "$host" \ "emacsclient -t -a '' -s server" sleep $delay exit_code=$? if [[ $exit_code -eq 0 ]]; then echo "[INFO] normal exit, reset delay" delay=2 else echo "[WARN] abnormal exit (code=$exit_code), retrying in ${delay}s..." # exponential backoff(最大 30s) (( delay < 30 )) && delay=$((delay * 2)) (( delay > 30 )) && delay=30 fi done }
Behavior and notes
- The function prints connection attempts with timestamps.
- A normal
emacsclientexit (exit code 0) resets the backoff delay to 2s. - Nonzero exit codes trigger a retry after
delayseconds;delaydoubles each failure until it reaches 30s. - The
traponINTprints a stop message and returns to the shell. - The
sshoptions used:- =ServerAliveInterval=30: send keepalive every 30s.
- =ServerAliveCountMax=3: allow three missed responses before disconnect.