2013-05-07 27 views
4

我有一些困難,理解什麼是寫在我的Ubuntu的.bashrc這是部分顯示在下面。 這是我不明白:瞭解這個.bashrc腳本(花括號,eval,...)

  • 什麼是大括號的目的和:之後使用的-/+符號? (例如:$ {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\]\[email protected]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ' 
    else 
        PS1='${debian_chroot:+($debian_chroot)}\[email protected]\h:\w\$ ' 
    fi 
    

回答

9

${var:-default}意味着$var if $var is defined and otherwise "default"

${var:+value}意味着if $var is defined use "value"; otherwise nothing

第二個可能看起來有點怪異,但你的代碼片段展示了一個典型用途:

${debian_chroot:+($debian_chroot)} 

這意味着「如果$ debia定義了n_chroot,然後將其插入括號中。「

上面的「定義」是指「設置爲某個非空值」。 Unix shell通常不會區分未設置的變量和設置爲空字符串的變量,但如果使用未設置的變量,則可以告訴bash引發錯誤條件。 (您可以用set -u進行此操作。)在這種情況下,如果從未設置debian_chroot,則$debian_chroot將導致錯誤,而${debian_chroot:-}將使用$debian_chroot(如果已設置),否則爲空字符串。

+1

謝謝。我不知道括號內的子殼。我也找到了這個鏈接來回答我的問題:http://wiki.bash-hackers.org/syntax/pe。不過我發現'$ {debian_chroot: - }'很奇怪。這不等於簡單的'$ debian_chroot'嗎? – Gradient 2013-05-07 06:10:19

+3

@Gradient如果使用'set -u',則使用unset變量的嘗試將被視爲錯誤,而不是展開爲空字符串。 '$ {debian_chroot: - }'將明確地將未設置的變量擴展爲空字符串,從而避免該錯誤。 – chepner 2013-05-07 11:16:20