Ubuntu – Toggle format of gnome terminal prompt string by command

bashgnome-terminal

My terminal has a default prompt format like this one:

username@boxname /path/to/current/directory $

The code that produces it looks like this: (it has some color definitions too)

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\]'

If the path to the current directory gets too long it becomes unpleasant to work with the terminal because you constantly break lines. In such cases I would prefer a format that produces a shorter string like this one:

username@boxname current_dir_name $

The code that produces it would look like this (again with color):

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] $(basename ${PWD}) \$ \[\033[00m\]'

Does anyone know how I could easily toggle the format of the current terminal window from one style to the other by just typing for example: prompttoggle?

Best Answer

Store both your long and short PS1 variables under a different name:

PS1short='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\]'
PS1long='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] $(basename ${PWD}) \$ \[\033[00m\]'

Make sure to set PS1to one of them initially:

PS1="$PS1long"

Then you can make an alias like this to toggle between the two PS1 values:

alias prompttoggle='if test "$PS1" = "$PS1long" ; then PS1="$PS1short" ; else PS1="$PS1long" ; fi'

Adding all four lines to your ~/.bashrc file will ake the command available in your Bash sessions, here are they again for easier copying:

PS1short='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\]'
PS1long='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] $(basename ${PWD}) \$ \[\033[00m\]'
PS1="$PS1long"
alias prompttoggle='if test "$PS1" = "$PS1long" ; then PS1="$PS1short" ; else PS1="$PS1long" ; fi'