Adjust the Length of Your Bash Prompt on the Fly

John John (304)
5 minutes

As a developer, I've customized my bash prompt to always show the current git branch if I'm in an initialized git repository. This is convenient, but it can make for a very long bash prompt. When I need more space, it's nice to be able to shorten the bash prompt on the fly.

Posted in these interests:
h/webdev60 guides
Bash
h/bash5 guides

According to the gnu.org bash reference regarding the PROMPT_COMMAND. If set, the value is interpreted as a command to execute before the printing of each primary prompt. One way to change your prompt on the fly is to simply set the value of PROMPT_COMMAND.

josephtyler@tylermbp[~] # PROMPT_COMMAND='PS1=# '

I've set two functions in my bashrc file to make this process easier. I've called the functions eep for expand prompt and ccp for contract prompt but you can call them whatever you'd like. Open your bashrc file to edit:

vim ~/.bashrc

Add the following at the end:

INITIAL_PROMPT_COMMAND=$PROMPT_COMMAND
function ccp() {
    PROMPT_COMMAND="PS1='# '"
}
function eep() {
    PROMPT_COMMAND=$INITIAL_PROMPT_COMMAND
}

The first line simply sets the initial command prompt to a new variable so that we can access it later.

INITIAL_PROMPT_COMMAND=$PROMPT_COMMAND

The next two lines are functions eep and ccp that you can use to expand and contract your bash prompt.

After saving this file, you'll need to source it for it to take effect.

source ~/.bashrc
John John (304)
2 minutes

When you're using git routinely, it's helpful to know which branch you're currently on without having to type git status or git branch.