exvx
exvx

Reputation: 31

Make prompt only display directory when not at $HOME?

I'd like to prevent my terminal prompt from displaying the directory I'm in when I'm at my home directory.

I'm using zsh. This is my prompt config:

PROMPT=''

# Formatting
PROMPT+='%F{8}' # dark grey

# Non zero exit codes
PROMPT+='%(?..[Exit code %?] )'

# PID when relevant
if [[ $! -ne 0 ]]; then
    PROMPT+='[PID $!] '
fi

# Current dir path
PROMPT+='[%~] '

# Formatting reset
PROMPT+='%f' # color reset

Upvotes: 3

Views: 273

Answers (1)

Adaephon
Adaephon

Reputation: 18339

setopt PROMPT_SUBST
PROMPT+='$([[ $PWD != $HOME ]] && echo "[%~] ")'

Explanation

  • setopt PROMPT_SUBST enables parameter expansion ($name), command substitution ($(command)) and arithmetic expansion ($[exp] or $((exp))) within the prompt
  • PROMPT+='…' appends to the prompt. Note that you need to use single quotes here so that the contents are not expanded during definiton but only when the prompt is shown.
  • $(command) runs command and substitutes its output, e.g. $(echo foo) would be replaced with "foo".
  • [[ exp ]] evaluates a conditional expression. It will return zero only if the expression is true. Note that [[ exp ]] is built-in syntax of zsh, while the similar [ exp ] would run the external [ (aka test) command.
  • PWD contains the current working directory.
  • HOME contains the home directory of the current user.
  • != tests for inequality.
  • && runs the command to the right only if the command to the left was successful (that is, returned zero)
  • echo "[%~] " prints the (partial) prompt string. Note that double quotes are used so that the surrounding single quotes are not closed prematurely.

Upvotes: 3

Related Questions