6

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 Answers 2

6

Since Bash 5.1, PROMPT_COMMAND can be an array; you can add your own command as the first one to be executed with

PROMPT_COMMAND=(mycommand "${PROMPT_COMMAND[@]}")

This also works if the existing value of PROMPT_COMMAND contains multiple commands in a single string.


For older Bash, such as the stock macOS bash, you can 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.

2
# 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'

You must log in to answer this question.

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