stoneman
stoneman

Reputation: 15

How can I set a conditional space succinctly in bash?

I am simply modifying by .bash_profile file so it can display my current git branch. It works, but I just want to improve the formatting a bit.

Here is what I am currently doing:

export PS1="${COL1}\u: ${COL2}\w${COL3} \$(git branch 2>/dev/null | grep '^*' | colrm 1 2)${NCOL} > "

If there is a branch present in the directly, it works properly. If there is no branch, the 2>/dev/null will get rid of the error, however, there will be an awkward extra space present before and after the empty git branch because it is empty.

Is there an easy way to make this space only appear, without having to create a separate function that'll include/not include a space accordingly?

Upvotes: 0

Views: 101

Answers (2)

chepner
chepner

Reputation: 531858

It's easier to build up the value of PS1 from within PROMPT_COMMAND than to embed what amounts to a small script in PS1 itself.

prompt_cmd () {
    PS1="${COL1}\u: ${COL2}\w${COL3}"
    git_info=$(git branch 2>/dev/null | grep '^*' | colrm 1 2)
    if [[ $git_info ]]; then
        PS1+="$git_info "
    fi
    PS1+="${NCOL} > "
}
PROMPT_COMMAND=prompt_cmd

Just prior to displaying the prompt, the code stored in PROMPT_COMMAND (in this case, a single function call) is executed. prompt_cmd builds the value of PS1 from scratch each time.

Upvotes: 0

DevSolar
DevSolar

Reputation: 70333

Instead of making the spaces in question part of the unconditional part of PS1, why not make them part of the git substitution?

export PS1="${COL1}\u: ${COL2}\w${COL3}\$(git branch 2>/dev/null | grep '^*' | colrm 1 1 | sed 's/$/ /')${NCOL}> "

colrm 1 1 instead of colrm 1 2 keeps the leading space from the branch, e.g. * master.

sed 's/$/ /' replaces end-of-line with a space (and end-of-line). If git branch errors out, there is no line, so no space here either.

Upvotes: 1

Related Questions