简体   繁体   English

如果远程运行,只在bash提示符中列出主机?

[英]Only list host in the bash prompt if running remotely?

I'm trying to modify my Bash prompt to my will; 我正试图按照我的意愿修改我的Bash提示; this is how $PS1 looks at the moment (with colors edited out for clarity): 这就是$PS1看的样子(为了清晰起见,为了清晰起见了颜色):

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? 如果我在本地运行当前的Bash会话而不是访问远程服务器,我是否可以调整提示,以便隐藏@tablet-2710p-ubuntu位(由@\\h表示)?

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. 我还宁愿不对其进行硬编码(例如,只是替换任何出现的tablet-2710p-ubuntu )以便于移植,以及以后更改主机名。

As brought out in How can I detect if the shell is controlled from SSH? 我所知如何检测shell是否受SSH控制? , if either of the variables $SSH_CLIENT or $SSH_TTY are set, it means you are connecting through SSH. ,如果设置了任何变量$SSH_CLIENT$SSH_TTY ,则表示您通过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): 如果您使用的是基于Debian的系统(例如Ubuntu),您可以将.bashrc编辑为类似的东西,以达到预期的效果(请注意, PS1设置的字符串必须用双引号定义 ,而不是单引号,默认情况下):

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. 附注:这些更改应在您通过SSH连接的服务器上的.bashrc (或.profile ,具体取决于分发)上进行 Setting them in your own local Bash profile has no effect on what is displayed when you connect to other remote servers. 在您自己的本地Bash配置文件中设置它们对连接到其他远程服务器时显示的内容没有影响。

Do you want something like below? 你想要下面的东西吗? :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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