KSH - Parameter substitution

03 Sep 2023

Here, the parameter substitution of the KornShell (precisely: pdksh) is introduced. The KornShell is the standard shell in OpenBSD.

A parameter substitution is a way to access variables in ksh. Accessing variables works equally simple as in other shells. It takes the form of $variable. The OpenBSD manual page of ksh(1) lists seven different ways how to assign variables. These are: implicit set by shell, import from environment, direct assignment, via command, inside a loop and with substitution.

The assignment via substitution is used with the special ${variable} form. Appending a colon with -, +, = or ? results in different checks to make sure the variable is e.g. set or not null and continues assigning the given value if that check is true.

The most interesting part of this special form of parameter substitution are the pattern matching functions. Using # or % it's possible to delete matched text from the beginning or the end of the variable content. Personally I've found some differences between the OpenBSD pdksh and a ksh93 downloaded from an Ubuntu repository. The pdksh is missing the definition of character classes ([:digit:]), a regular expression substition (${var//x/X}) and some minor variants that can be used inside square brackets are not available. A few working examples are:

var="hello world"
echo ${var#h} # ello world
echo ${var##*([a-z])} # world
echo ${var%%*([a-z])} # hello
echo ${var#he@(ll|llo)} # o world
echo ${var##he@(ll|llo)} # world
  

Though a little bit limiting than other shells, I generally like the control over the greadyness of the pattern matching mechanism you get with the single or double modifiers (% and #). The missing character classes are a pity, but can be easily defined before use. Sure, there are shells that are way more fancy and modern than ksh, but it feels like a tool that everyone understands and is able to use. Like a knife or a screwdriver. I think I'll continue writing about other features of the shell.

Further reading: Learning the Korn Shell (2nd edition), Arnold Robbins and Bill Rosenblatt, 978-0-596-00195-7