HomeSoftwareGamesMusicForum

Shell programming

This is about scripts and functions for bash and ksh (precisely, ksh93). Both shells are freely available and easy to install under Linux. [1] I use bash mainly for interactive work (i.e., as login shell) and for simple scripts. There are some pragmatic reasons for using bash: It is the standard Linux shell, so one has to know it anyway, and it offers more comfort in interactive mode than ksh. On the other hand, ksh is better suited for complex scripts because of its advanced features (associative arrays, references, structured variables etc.).

Most of the shell scripts and functions shown here work well with both bash and ksh. Only in a few cases the shell differences were too big for a common version.

Functions use local variables wherever possible, in order to keep the shell environment intact. Some of them, however, have to use eval or the ksh declaration syntax name(), which may lead to coincident names in function and current shell. To keep the probability of such collisions low, all names declared in those functions start with the prefix functionname_ and end with _, e.g. vared_i_. Should it turn out that this isn't sufficient, the weirdness of the local naming scheme can be increased.

Files can be downloaded individually or as a whole (button at the left). Shorter functions are quoted in the text. All of them require a sufficiently new shell version. They have been tested with bash-3.2 and ksh-1993-12-28s+ (2007-11-05).

Compatible scripts?

Some people keep advising others in newsgroups to write "compatible" scripts, that is, to ignore the capabilities of modern shells and restrict themselves to the archaic Bourne shell standard. This may make sense for users who desperately want their scripts to run on the oldest and obscurest unixoid systems (though even then there is no guarantee). Those, however, who are satisfied with scripts that run on any current Linux system, or who simply write for themselves, can happily ignore this advice. The features of modern shells have been introduced for good reasons (to make programming easier and safer), and that's why they are used consequently in the scripts presented here.


[1] Of course there are more shells, each of which has its pros and cons. I concentrate on bash and ksh because I'm familiar with them, and don't participate in religious shell wars.

up
Created 2011-08-11 by mopcoge