What does "${debian_chroot:+($debian_chroot)}" do in my terminal prompt?

In my terminal prompt definition in my .bashrc file, among other things, I have this snippet of code:

${debian_chroot:+($debian_chroot)}

What does this do, and do I need it?


Solution 1:

The important part to answer this question is this snippet from /etc/bash.bashrc:

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

It means if the variable $debian_chroot is empty and the file /etc/debian_chroot exists and is readable the variable is set to the content of the file.

Now what is this for? The file /etc/debian_chroot is when you have a chrooted debian system inside another debian system (ubuntu is based on debian). So this is for a better overview. To distinguish whether you are in the chroot or not.

When you have a chroot of another system for example in /srv/nfs4/netboot/ you can set a name for this chroot in /srv/nfs4/netboot/etc/debian_chroot (in my case it's a nfs4 pxe netboot drive):

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

And then when you chroot inside:

chroot /srv/nfs4/netboot/

Your prompt looks like this:

(netboot)user@host:~#

Solution 2:

Generally, ${var:+value} means:

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

The debian_chroot variable is defined in /etc/bash.bashrc file. It takes the content of /etc/debian_chroot file if this file exists and is readable. By default this file doesn't exists.

For more details, see:

  • What is $debian_chroot in .bashrc?
  • Understand this .bashrc script (curly braces, eval, …)

Now, to understand better what exactly it is happening there, do the following in terminal:

radu@Radu:~$ PS1='${var:+($var)}\u@\h:\w\$ '
radu@Radu:~$ var="test"
                  ----
                   |
  ------------------
  |
  V
(test)radu@Radu:~$ var=""
radu@Radu:~$ var="and so on"
(and so on)radu@Radu:~$

Solution 3:

If the environment variable $debian_chroot exists and is not empty ${debian_chroot:+($debian_chroot)} is replaced by ($debian_chroot) (that is the value of $debian_chroot with parens around it).

$debian_chroot is set in /etc/bash.bashrc to the contents of /etc/debian_chroot if that file exists (it doesn't by default) and $debian_chroot doesn't have a value yet.

${debian_chroot:+($debian_chroot)} is usually used to define your Bash prompt, for example

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

As the name suggests you can use this variable to indicate which chroot you are in by placing etc/debian_chroot into your chroot root folders.

If you don't know what a chroot is chances are you don't need that ;-) But you still may abuse it to include some other information into your Bash prompt

By default it doesn't do anything.