【问题标题】:Understand this .bashrc script (curly braces, eval, ...)理解这个 .bashrc 脚本(花括号、eval、...)
【发布时间】:2013-04-30 21:59:42
【问题描述】:

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

  • 大括号和-/+ 符号在: 之后的用途是什么? (例如:${debian_chroot:-} 和 ${debian_chroot:+($debian_chroot)})

  • eval 命令。

  • 以下 sn-p 代码的工作原理。

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

【问题讨论】:

    标签: bash eval curly-braces


    【解决方案1】:

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

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

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

    ${debian_chroot:+($debian_chroot)}
    

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

    上面,“定义”的意思是“设置为一些非空值”。 Unix shell 通常不区分未设置的变量和设置为空字符串的变量,但是如果使用未设置的变量,bash 可以被告知引发错误条件。 (您使用set -u 执行此操作。)在这种情况下,如果从未设置过debian_chroot,则$debian_chroot 将导致错误,而${debian_chroot:-} 将使用$debian_chroot(如果已设置),否则为空字符串。

    【讨论】:

    • 谢谢。我不知道括号中的子shell。我还找到了回答我问题的链接:wiki.bash-hackers.org/syntax/pe。我仍然觉得${debian_chroot:-} 很奇怪。不就等同于$debian_chroot吗?
    • @Gradient 如果使用set -u,尝试使用未设置的变量将被视为错误,而不是扩展为空字符串。 ${debian_chroot:-} 会将未设置的变量显式扩展为空字符串,从而避免该错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2023-03-26
    • 2021-05-16
    • 2014-10-27
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多