Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understand this .bashrc script (curly braces, eval, ...)

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
    
like image 217
Gradient Avatar asked May 07 '13 03:05

Gradient


People also ask

What does curly brackets mean in shell script?

The end of the variable name is usually signified by a space or newline. But what if we don't want a space or newline after printing the variable value? The curly braces tell the shell interpreter where the end of the variable name is.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

How do you escape brackets in bash?

Bash Character Escaping. Except within single quotes, characters with special meanings in Bash have to be escaped to preserve their literal values. In practice, this is mainly done with the escape character \ <backslash>.


1 Answers

${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.

like image 108
rici Avatar answered Nov 05 '22 01:11

rici