Is it possible to use bash parameter expansion to replace $VAR with '' if and only if it matches some 'value' exactly?

There is the syntax ${VAR#value} which removes value the beginning of $VAR and similarly ${VAR%value} which removes it from the end. This does replace value with '', but if $VAR is something like value1 or 1value, it could replace it with 1, but in those cases it should remain unchanged.

I know I can do this with an if statement, but I am trying to add something to my PS1 that is not shown if it equals some value, which is why I need to use parameter expansion, or some other kind of inline syntax.

2 Answers 2


I'd probably go for parameter expansion of the $() kind:

PS1='$( [[ "${VAR}" == value ]] || printf %s "${VAR}" )$ '

Beware it removes trailing newline characters from the value of $VAR.


If switching to zsh is an option, you can use ${VAR:#value} or the ksh93 style ${VAR/#%value}.

${var/pattern[/replacement]} comes from ksh93 and has also been copied by bash. ksh93 also lets you anchor the search at the start with ${var/#pattern} or end with ${var/%pattern} but doesn't let you combine both. bash doesn't either but zsh does with ${var/#%pattern}.

See info zsh 'Parameter Expansion' for details.

With the extendedglob option on, you also get (#s) and (#e) glob pattern operators (Globbing Flags) that match respectively at the start (like regex ^) and end (like regex $) of the subject, so after set -o extendedlob, you can also use ${VAR/(#s)value(#e)} or ${VAR#value(#e)} or ${VAR%(#s)value}.

If it's about prompt expansion, you'd be better of preparing the text you want to include in a precmd hook (or $PROMPT_COMMAND in bash), something like:

prompt-from-VAR() {
  case $VAR in
    (value) psvar[1]=;;
    (something-else) psvar[1]=OTHER;;
    (*) psvar[1]=$VAR;;
autoload add-zsh-hook
add-zsh-hook precmd prompt-from-VAR
PS1='%1v$ '

(here using $psvar and %v instead of the more dangerous prompsubst option).

In bash that has no equivalent to psvar or precmd hooks:

  case $var in
    (value) promt_VAR=;;
    (something-else) prompt_VAR=OTHER;;
    (*) prompt_VAR=$VAR;;
PS1='${prompt_VAR}$ '

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .