Jul 032014
 

It is nice to make a shell environment more pleasant to use in many ways, but it is also helpful to ensure that the process degrades gracefully …

For example, I have a section in my .zshrc which creates an ls alias to use human-readable values, and to colourise the output :-

ls --color=auto > /dev/null 2>&1
#       Just collect the exit status ...
if [ "$?" = 0 ]
then
  # If there is no error then use the --color option
  alias ls='ls -h --color=auto'
else
  alias ls='ls -h'
fi

Thus when logging into a system that has an ls command that lacks the –color option, the alias will not create an ls command that immediately fails. Now whilst such systems are getting rather more rare than in the past, this graceful degradation is still useful as a principle. Whether creating shell aliases, or more generally.

As another example, I have a shell alias (page or also pg) that I use to invoke a “pager” like more, less, pg, or my preferred choice, most. The relevant section within the zshrc file is :-

for candidate in more less most
do
  p=$(which $candidate)
  if [ "$?" = "0" ]
  then
    alias pg=$candidate
    alias page=$candidate
    PAGER=$candidate
  fi
done

This repeatedly sets up the two aliases (and sets the PAGER environment variable) if the candidate pager is available; otherwise the aliases are left alone. In other words, this works through a list of candidates in order from most available to least available (but preferred) to select one. Once used to using page as a command, I no longer need to worry about if most is installed on a system.

A very similar loop is used to generate an alias called vim which will always work (at least when vi is available).
 

Jun 192014
 

… or a red ✗. Incidentally, if your browser doesn’t show ticks (✓), crosses (✗), and a right pointing double arrow (») properly, this posting may look a bit odd.

As in :-

2014-06-19_1934

The aim here is to make the zsh prompt (a Unix shell) start with a green ✓ (tick) if the previous command’s exit status was zero, and a red ✗ (cross) if the previous command’s exit status was non-zero. A tiny thing, but both useful and fun.

The first thing I need is a set of variables containing terminal sequences for setting colours. Fortunately zsh comes with a set of suitable functions; even if they’re poorly named :-

autoload -U colors && colors

The next thing is to perform a test to see if the current terminal type is worth setting a fancy prompt for. In some cases – such as when using the plain Linux console, or when things are broken enough that the terminal type isn’t set properly – it is worth avoiding setting a prompt. I do this by setting up an array containing a list of terminal types that I think it is worth setting a fancy prompt for :-

fancyterms=()
fancyterms=(xterm xterms dtterm iris-ansi xterm-256color)

(Some of that list is very historical!)

The test for whether to set a fancy prompt is somewhat tricky … it uses a ‘reverse subscripting’ flag in the array lookup to search the array for the string :-

if [[ ${fancyterms[(r)$TERM]} == "$TERM" ]] 
then
  echo Fancy prompt
else
  echo Plain prompt
fi

And lastly, I actually set the prompt :-

export PROMPT="%(?.%{$fg[green]%}✓ %{$reset_color%}.%{$fg[red]%}✗ %{$reset_color%})%B%n@%m»%b "

Which is not exactly the easiest string to understand, but breaking it up :-

  1. The %{$fg[green]%} sequence sets the colour to green, the ✓ is fairly self-explanatory, and the %{$reset_color%} sets the colours back to normal.
  2. Similarly the %{$fg[red]%} sets the colour to red, the ✗ should also be self-explanatory, and the %{reset_color%} does as before.
  3. The sequence %{ … %} is very important as any output that does not advance the cursor should be contained within these. This allows zsh to count the number of visible characters within the prompt so that various screen operations happen in the right location. Judging by how often this is emphasised (and the fact that I made a mistake with it myself), it looks to be a very common problem.
  4. The sequence %{?.True.False%} tests the exit status of the previous command and if true outputs the first string and if false outputs the second string.
  5. The sequence at the end – %B%n@%m»%b – turns bold on (%B), outputs the username (%n), outputs an “@”, outputs the short machine name (%m), outputs a literal “»”, turns off cold (%b), and finally adds a space to the prompt.

Putting it all together, I get :-

# Now the prompt
autoload -U colors && colors
#       Enable colour variables (used in prompt)
fancyterms=()
fancyterms=(xterm xterms dtterm iris-ansi xterm-256color)
#       An array of 'fancy' terminal types that we do more for … as in a funky PROMPT.

if [[ ${fancyterms[(r)$TERM]} == "$TERM" ]] 
then
        precmd () { print -Pn '\e]2;%n@%m - %~^G' }
        # Put the hostname in the Window title/Tab title
        export PROMPT="%(?.%{$fg[green]%}✓ %{$reset_color%}.%{$fg[red]%}✗ %{$reset_color%})%B%n@%m»%b "
        # And set a really fancy prompt.
else
        # If we don't recognise the terminal type, don't attempt to be quite so ambitious
        # with the prompt.
        export PROMPT=$'%B%n@%m - %~\n%#%b '
fi

This is still a little bit plain compared with what some people do with their prompts, but it is right for me (at least for now).