简体   繁体   中英

Only list host in the bash prompt if running remotely?

I'm trying to modify my Bash prompt to my will; this is how $PS1 looks at the moment (with colors edited out for clarity):

PS1='\u@\h:\w\$ '

Which results in:

andreas@tablet-2710p-ubuntu:~$ 

Can I tweak the prompt so it hides the @tablet-2710p-ubuntu bit (represented by @\\h ) if I'm running the current Bash session locally , rather than accessing a remote server?

I'd also rather not hard-code it (for instance, just replacing any occurrence of tablet-2710p-ubuntu ) for portability's sake, and in case the host name is changed later.

As brought out in How can I detect if the shell is controlled from SSH? , if either of the variables $SSH_CLIENT or $SSH_TTY are set, it means you are connecting through SSH.

If you are on a Debian-based system (such as Ubuntu) you can edit your .bashrc to something like this in order to achieve the desired effect (note that the string that PS1 is set to has to be defined with double quotes , not single quotes as it is by default):

if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
    if [ "$color_prompt" = yes ]; then
        host="@\[\033[1;34m\]\h\[\033[00m\]"
    else
        host="@\h"
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u\[\033[00m\]${host}:\[\033[01;34m\]\w\[\033[00m\]\$ "
else
    PS1="${debian_chroot:+($debian_chroot)}\u${host}:\w\$ "
fi
unset host
unset color_prompt force_color_prompt

Which results in the following:

BASH:在本地运行时隐藏主机,在通过SSH连接时显示主机

Side note: These changes should be made on the .bashrc (or .profile , depending on the distribution) on server you are connecting to over SSH. Setting them in your own local Bash profile has no effect on what is displayed when you connect to other remote servers.

Do you want something like below? :

if [ "$SSH_CONNECTION" ]; then 
    PS1='\u@\h:\w\$ '
else
    PS1='\u:\w\$ '
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM