理解这个.bashrc脚本(花括号,eval,......)(Understand this .bashrc script (curly braces, eval, …))

我很难理解我的ubuntu .bashrc写的内容,如下所示。 这是我不明白的:

花括号的目的是什么,以及后面使用的- / +符号是什么? (例如:$ {debian_chroot: - }和$ {debian_chroot:+($ debian_chroot)})

eval命令。

以下代码片段如何工作。

[ -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

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

最满意答案

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

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

第二个可能看起来有点奇怪,但你的代码片段显示了一个典型的用法:

${debian_chroot:+($debian_chroot)}

这意味着“如果定义了$ debian_chroot,则将其插入括号中。”

上面,“已定义”表示“设置为某些非空值”。 Unix shell通常不区分未设置的变量和设置为空字符串的变量,但是如果使用未设置的变量,则可以告诉bash引发错误条件。 (你用set -u来做。)在这种情况下,如果从未设置$debian_chroot , $debian_chroot将导致错误,而${debian_chroot:-}将使用$debian_chroot如果已设置),否则为空字符串。

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

更多推荐