Bash编程,为什么反斜杠是必要的?

时间:2017-11-28 07:58:54

标签: bash

为了显示工作git存储库的分支名称,我对PS1变量进行了以下设置。

function parse_git_branch {
    local branch
    # Direct stderr to null device in case it's not in a git repo.
    branch=$(git symbolic-ref HEAD 2> /dev/null);

    # Zero length if it's not in a git repo.
    if [ ! -z $branch ];
    then
      # remove the matched part of pattern.
      echo "(${branch#refs/heads/})";
    fi
}

PS1="\n\w$BASH_LIGHT_GREEN \$(parse_git_branch)$BASH_WHITE\n$ ";

问题: 为什么我必须在美元符号命令之前加上反斜杠? 如果我删除反斜杠,它不会正确显示分支名称。

1 个答案:

答案 0 :(得分:6)

  

注意命令替换的美元符号之前的反斜杠是很重要的。没有它,外部命令只执行一次:当PS1字符串被读入环境时。对于此提示,这意味着无论使用多长时间,它都会显示相同的时间。反斜杠保护$()的内容不受立即shell解释的影响,因此每次生成提示时都会调用date。

Source TLDP doc