Pei Hsiang Hung
Pei Hsiang Hung

Reputation: 81

Bash programming, why the backslash is necessary?

To show the branch name of the working git repository, I have the following setting for PS1 variable.

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$ ";

Question: Why do I have to precede the dollar sign command with a backslash? If I remove the backslash, it doesn't show the branch name correctly.

Upvotes: 0

Views: 63

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

It's important to notice the backslash before the dollar sign of the command substitution. Without it, the external command is executed exactly once: when the PS1 string is read into the environment. For this prompt, that would mean that it would display the same time no matter how long the prompt was used. The backslash protects the contents of $() from immediate shell interpretation, so date is called every time a prompt is generated.

Source TLDP doc

Upvotes: 6

Related Questions