在我的终端提示中“$ {debian_chroot:+($ debian_chroot)}”做了什么?

在我的.bashrc文件中的终端提示定义中,除此之外,我还有以下代码片段:

 ${debian_chroot:+($debian_chroot)} 

这是做什么的,我需要它吗?

回答这个问题的重要部分是来自/etc/bash.bashrc这个片段:

 if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then debian_chroot=$(cat /etc/debian_chroot) fi 

这意味着如果变量$debian_chroot为空并且文件/etc/debian_chroot存在且可读,则将变量设置为文件的内容。

现在这是为了什么? 文件/etc/debian_chroot是你在另一个debian系统中有一个chroot debian系统(ubuntu基于debian)。 所以这是为了更好的概述。 要区分你是否在chroot。

如果你有/srv/nfs4/netboot/的另一个系统的chroot,你可以在/srv/nfs4/netboot/etc/debian_chroot设置这个chroot的名称(在我的例子中它是一个nfs4 pxe netboot驱动器):

 user@host:~# echo "netboot" >/srv/nfs4/netboot/etc/debian_chroot 

然后当你在里面chroot:

 chroot /srv/nfs4/netboot/ 

您的提示符如下所示:

 (netboot)user@host:~# 

通常, ${var:+value}表示:

 if $var is defined; then use 'value'; else do nothing 

debian_chroot变量在/etc/bash.bashrc文件中定义。 如果此文件存在且可读,它将获取/etc/debian_chroot文件的内容。 默认情况下,此文件不存在。

有关详细信息,请参阅:

  • 什么是.bashrc中的$ debian_chroot?
  • 理解这个.bashrc脚本(花括号,eval,……)

现在,为了更好地了解它到底发生了什么,请在终端中执行以下操作:

  radu@Radu:~$ PS1 ='$ {var:+($ var)} \ u @ \ h:\ w \''
 radu @ Radu:〜$ var =“test”
                   ----
                    |
   ------------------
   |
   V
 (测试)radu @ Radu:〜$ var =“”
 radu @ Radu:〜$ var =“等等”
 (等等)radu @ Radu:〜$ 

如果$debian_chroot变量$debian_chroot存在并且不为空${debian_chroot:+($debian_chroot)}被替换为($debian_chroot) (这是$debian_chroot的值,其周围有parens)。

$debian_chroot/etc/bash.bashrc中设置为/etc/debian_chroot的内容,如果该文件存在(默认情况下不是这样)并且$debian_chroot还没有值。

${debian_chroot:+($debian_chroot)}通常用于定义你的Bash提示符,例如

 PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ ' 

顾名思义,您可以使用此变量通过将etc/debian_chroot放入chroot根文件夹来指示您所在的chroot。

如果你不知道chroot是什么机会你不需要;-)但是你仍然可以滥用它来在你的Bash提示中包含一些其他信息

默认情况下,它不执行任何操作。