1

Mac's Terminal comes with a default PROMPT_COMMAND that checks the history and updates the current working directory (title of the tab):

Add echo $PROMPT_COMMAND to the top of your .bash_profile and you'll see:

shell_session_history_check; update_terminal_cwd

I want to add my own PROMPT_COMMAND without over-writing the default. The default should come before my custom PROMPT_COMMAND with a semicolon and space to separate the two.

Note that some programs (such as IntelliJ and VS Code) don't have a default! So I wouldn't want to include the space/semicolon in that case.

2

I use parameter expansion with :+ for this:

${parameter:+word}
If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

An example:

$ unset var
$ var=${var:+"$var; "}XXX
$ echo "$var"
XXX
$ var=abc
$ var=${var:+"$var; "}XXX
$ echo "$var"
abc; XXX

So to keep the existing command with ; appended, I use

PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND; "}'mycommand'

If PROMPT_COMMAND is empty before, it contains just mycommand afterwards, and if it wasn't, ; is inserted between the existing command and mycommand.

1
# If PC contains anything, add semicolon and space
if [ ! -z "$PROMPT_COMMAND" ]; then
    PROMPT_COMMAND="$PROMPT_COMMAND; "
fi

# Add custom PC
PROMPT_COMMAND=$PROMPT_COMMAND'CUSTOM_PC_HERE'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.