Donnerstag, 8. Oktober 2015

Limit the length of the path in a Bash prompt

It is possible to define the Bash prompt by setting the PS1 variable. A typical prompt definition is a combination of user name, host name and working directory:

# export PS1='\u@\h:\w\$ '

But this makes it difficult to dive into really deep directory tries. If the directory gets longer than the width of the terminal, the prompt will span two lines. And if you have to use a limited terminal on a Solaris system, the screen gets totally messed.

For this situations it is possible to define the prompt in that way, that only the last directory is part of the prompt.

# export PS1='\u@\h:\W\$ '

But having only one directory is often not enough. If you have some source packages, each containing a src directory, it not possible any more to distinguish them.

The best solution for the problem would be to clip the path to a maximum length and indicate the clipping by some kind of special character. That can be done by the following prompt definition.

# export PS1='\u@\h:$(p=${PWD: -30};p=${p:+<$p};echo ${p:-$PWD})\$ '

The definition uses Bash's parameter expansion feature in three steps. First a variable p is defined and 30 characters of PWD are taken from the right. If PWD is less than 30 characters p is an empty string. Otherwise p is the clipped part of PWD. In the next step p gets prefixed with the '<' character, if it is set. Otherwise it will be still undefined. And in the last step either p will be printed, if it is set, or PWD, if p is still undefined. This means that either the clipped and prefixed part of PWD gets printed, if it is longer than 30 characters, or PWD is printed without any modifications.

Keine Kommentare: