Tcsh Aliases (1 of 3): Introduction to expanding tcsh aliases and history substitutions

Although bash is the default shell on many systems, many Linux users still choose to use tcsh (the newer name for csh) because of the more powerful alias capabilities. Aliases let you create shortcuts to longer commands, which can save you time, but using them can lead to difficulties when you don’t know the actual command that you have run.

We have developed a free tool called tcshParser for turning aliases into real commands. In part 3 of this this blog series I will explain how that works and where you can find the tool. But first, let’s have a look at what aliases can do for you.

Most shells, including tcsh, provide an “alias” command which allows you to define new commands, which are typically abbreviations for longer commands. For example, you might like to abbreviate ls -l as ll. It won’t save you much typing, but if you define the following alias on the commandline:

alias ll ls -l

then typing ll /tmp will have the same effect as typing ls -l /tmp. Similarly, if you define the following alias

alias ls ls --color=tty

then ls src will have the same effect as ls --color=tty src

Recursive Aliases

One of the things that makes tcsh aliases so useful, is that you can define multiple aliases that will be applied repeatedly until the first word remains unchanged. For example

ll /tmp

is first expanded to

ls -l /tmp

Since the first word changed from ‘ll’ to ‘ls’,  ‘ls’ is itself expanded, resulting in

ls --color=tty -l /tmp

Even though the expansion has changed the command, this time the first word is unchanged so alias substitution stops.

Of course this flexibility means that you could create a loop, perhaps defining “a” to mean “b”, and “b” to mean “a”. But if you do that, tcsh will report “Alias loop” when you try to use either “a” or “b”.

History Substitution

Tcsh “history” commands are another way to reduce the amount you need to type. They can be used on the command line or in aliases. On the command line, history substitution allows you to reuse part or all of a previous command, and perhaps the best known history command is !!, which simply repeats the previous command. When used in an alias, history substitution is a way to refer to parts of command as it was before the alias was expanded.

As a slightly more interesting example of a history substitution, imagine that you have just run the command

$ ls onelongdirectoryname anotherlongdirectoryname

and you now want to run a slightly different command referring to just the first of those long names. Typing:

$ du --human -s !:1

has the same effect as typing the much longer command:

$ du --human -s onelongdirectoryname

There are many such history substitution commands. Check out the tcsh manual for more details.

Next time we’ll look at how aliases and history substitutions can work together.

Author: Richard Jordan is a developer at Ellexus