Mittwoch, 14. Oktober 2015

Using the last command in the Bash prompt

Today I had the idea that it might be useful to have the return value of the last command in the PUtty title. And next step is to put also the last command into the title.

The command history 1 prints the last command from the Bash history of commands. The Output is prefixed by a number and two spaces. The following Bash expression removes the prefix and prints just the command.

$(h=$(history 1);n=${h/% */};echo "${h#$n }")

First h is initialized with the whole history line. Then n is set to the remaining part of h after the longest match from the right up the a space is removed from h. And in the end h without the prefix stored in n is printed.

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\$ '
root@server:/tmp/aaa/bbb/ccc/ddd/eee/fff/ggg/hhh/jjj/kkk# 

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\$ '
root@server:kkk# 

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})\$ '
root@server:<cc/ddd/eee/fff/ggg/hhh/jjj/kkk# 

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.