Adjust the length of your bash prompt on the fly

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.

1

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 ($PS1One way to change your prompt on the fly is to simply set the value of PROMPT_COMMAND.

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

2

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