Previous Section  < Day Day Up >  Next Section

Recipe 17.10. Customizing the Bash Prompt for ssh

17.10.1 Problem

Sure, you know that the prompt changes to display the remote hostname when you're logged in via SSH. But it's just a dumb little black-and-white prompt, and it's easy to make mistakes, so you want a customized, colorful prompt to indicate when you have an active SSH login.

17.10.2 Solution

Customize the Bash prompt on the remote PCs. This example turns the prompt red and adds "ssh" to it.

Add these lines to the ~./bashrc for the remote account you want to log into:

if [ -n "$SSH_CLIENT" ]; then text=" ssh"

fi

export PS1='\[\e[0;31m\]\u@\h:\w${text}$\[\e[m\] '

When you log into this machine, the prompt will look like this, in red:

carla@server06:~ssh $

Only the prompt is red; all the other text will be your normal shell colors.

17.10.3 Discussion

Customizing the Bash prompt is practically a book topic in itself. The example in this recipe can easily be edited to suit your preferences. You don't have to use "ssh" or name the variable "text;" these can be anything you like. [\e[0;31m\] determines the text color—just change the numbers.

[\e[m\] turns off the colors, so that your commands and command output will return to the normal shell colors (Table 17-1).

Table 17-1. Bash prompt text colors

Black 0;30

Dark Gray 1;30

Blue 0;34

Light Blue 1;34

Green 0;32

Light Green 1;32

Cyan 0;36

Light Cyan 1;36

Red 0;31

Light Red 1;31

Purple 0;35

Light Purple 1;35

Brown 0;33

Yellow 1;33

Light Gray 0;37

White 1;37


This customization works by checking for the presence of the SSH_CLIENT environment variable. Then Bash knows to use the custom SSH prompt instead of the default prompt. To see this for yourself, log into a remote host via SSH, then run:

user@remotehost$ echo $SSH_CLIENT

192.168.1.5 33232 22

This only works on the remote prompt. Running it at the local prompt will return a blank line:

user@localhost$ echo $SSH_CLIENT

because once you complete an SSH login, the remote machine controls your local terminal, and the SSH client is running on the remote PC. That is why you have to customize ~/.bachrc on the remote hosts.

17.10.4 See Also

    Previous Section  < Day Day Up >  Next Section