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).