|
| 1 | ++++ |
| 2 | +date = '2025-04-20T20:07:49+02:00' |
| 3 | +draft = false |
| 4 | +title = 'Custom Prompt When Connected Over SSH' |
| 5 | +summary = 'To prevent me from deleting the wrong files...' |
| 6 | ++++ |
| 7 | + |
| 8 | +I use `zsh` with a theme called `robbyrussell` that makes my prompt very minimalistic. I already |
| 9 | +know who I am, and what machine I'm on, so the standard `user@host` prompt is just noisy. |
| 10 | + |
| 11 | +```bash |
| 12 | +➜ ~ echo "Hello" |
| 13 | +``` |
| 14 | + |
| 15 | +I quite like it, except when I SSH to my main machine at work, then it suddenly becomes difficult |
| 16 | +to remember which terminal is which. |
| 17 | + |
| 18 | +Let's prefix my prompt with the hostname, but only if I'm connected over SSH. |
| 19 | + |
| 20 | +## Customizing the prompt |
| 21 | + |
| 22 | +**TL;DR:** Add this snippet to your `~/.zshrc` or `~/.bashrc` (on the remote machine) |
| 23 | + |
| 24 | +```bash |
| 25 | +if [[ -n $SSH_CONNECTION ]] ; then |
| 26 | + PS1="[$(hostname)] $PS1" |
| 27 | +fi |
| 28 | +``` |
| 29 | + |
| 30 | +And your prompt will look like this when you connect to it |
| 31 | + |
| 32 | +```bash |
| 33 | +[some-pc-name] ➜ ~ echo "Hello" |
| 34 | +``` |
| 35 | + |
| 36 | +But why stop there? It's always nice with a bit of flair! So I came up with this: |
| 37 | + |
| 38 | +```bash |
| 39 | +if [[ -n $SSH_CONNECTION ]]; then |
| 40 | + hostname_string="%{$fg_bold[blue]%}[%{$fg_bold[yellow]%}%U$(hostname)%u%{$fg_bold[blue]%}]%{$reset_color%}" |
| 41 | + PS1="$hostname_string $PS1" |
| 42 | +fi |
| 43 | +``` |
| 44 | + |
| 45 | +And how we end up with this when I SSH into my laptop. |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +Ant that's good enough for me. |
| 50 | + |
| 51 | +## How does it work? |
| 52 | + |
| 53 | +`SSH_CONNECTION` is an environment variable that is set when you connect via SSH. We're just using |
| 54 | +it as a flag, but it contains the IP of the remote and local machine (see `man ssh`). |
| 55 | + |
| 56 | +`PS1` is another environment variable, the primary prompt string. This string is what defines your |
| 57 | +prompt. |
| 58 | + |
| 59 | +In the first example, I'm simply prepending the existing `PS1` variable with `[$(hostname)]`. In |
| 60 | +the second example, it's a bit more complicated. There `hostname_string` is formatted according to |
| 61 | +the section `EXPANSION OF PROMPT SEQUENCES` in `man zshmisc`. |
| 62 | + |
| 63 | +But we also make use of the variables `fg_bold` and `reset_color`. Which you can read more about |
| 64 | +in `man zshcontrib` under `OTHER FUNCTIONS`. |
| 65 | + |
| 66 | +## Further reading |
| 67 | + |
| 68 | +* `man zshall` - All `zsh` manuals in one big `man` page. |
| 69 | +* `man bash` |
0 commit comments