Question

I have some difficulty understanding what is written in my ubuntu's .bashrc which is shown in part below. Here is what I don't understand :

  • What is the purpose of curly braces and the -/+ symbols used after :? (ex. : ${debian_chroot:-} and ${debian_chroot:+($debian_chroot)})

  • The eval command.

  • How the following snippet of code works.

    [ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
    
    if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
        debian_chroot=$(cat /etc/debian_chroot)
    fi
    
    if [ "$color_prompt" = yes ]; then
        PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
    else
        PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
    fi
    
Was it helpful?

Solution

${var:-default} means $var if $var is defined and otherwise "default"

${var:+value} means if $var is defined use "value"; otherwise nothing

The second one might seem a little wierd, but your code snippet shows a typical use:

${debian_chroot:+($debian_chroot)}

This means "if $debian_chroot is defined, then insert it inside parentheses."

Above, "defined" means "set to some non-null value". Unix shells typically don't distinguish between unset variables and variables set to an empty string, but bash can be told to raise an error condition if an unset variable is used. (You do this with set -u.) In this case, if debian_chroot has never been set, $debian_chroot will cause an error, while ${debian_chroot:-} will use $debian_chroot if it has been set, and otherwise an empty string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top