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
?
Store both your long and short
PS1
variables under a different name:Make sure to set
PS1
to one of them initially:Then you can make an alias like this to toggle between the two PS1 values:
Adding all four lines to your
~/.bashrc
file will ake the command available in your Bash sessions, here are they again for easier copying:You can use a tiny
bash
function:The function above matches if the current
$PS1
containsbasename
, if yes, then thePS1
withoutbasename
is set otherwise the one withbasename
is set.Put the function in your
~/.bashrc
to get it available in all interactive sessions.Example:
Or... make two very tiny functions and add to the end of your
~/.bashrc
for a shortened prompt, type
promptshort
, to go back to the full path, typepromptlong
\W
shows the current working directory only so$(basename ${PWD})
is overkill imhoYou could combine into one function but "long" and "short" are descriptive and both have less keystrokes than "toggle" ;)
Instead of adding a line to override PS1 I prefer to tweak the code that sets it (for example, uncomment
force_color_prompt=yes
and edit the line after[ "$color_prompt" = yes ]; then
)Here's a
~/.bashrc
function definition that I personally use to reset/toggle my prompt from regular prompt to just$
. Adapt it as necessary to suit your needs.This is an answer to your problem (long directories break the command line) and not specifically to your question (how to change the command prompt on the fly.)
I solved this problem years ago with this prompt:
What this does:
This gives you all the space you need for your command, does not shift it right when you are in a deep directory structure, does not mangle the typing line with color codes (avoiding strange bugs that happen sometimes), while still giving you the colored hint on where the output of one command ended and the next one begun: