K-shawk!

Ok. I started writing this when I was standing in line to pick up an iPhone 4 (that’s right, this post has been that long in the making!), so this post was planned to be short with few examples!

I just wanted to introduce ksh93 to everyone (or as my very good friend calls it K-shawk!).

When it comes to shells most people know about sh, csh, ksh, bash etc. They know about strengths and weaknesses of each and what not. However, very few people know that there are 2 versions of ksh available out there.

  1. ksh – the most popular version packaged with pretty much all UNIX OSes. This is really ksh88. In other words, it’s the version of ksh that was implemented in 1988.
  2. ksh93 – this is not as popular as ksh88, but in my experience, it’s packaged in every commercial OS.

I highly recommend upgrading to ksh93 for all your shell scripts and interactive shell. Why? Simply because it has a lot of features that were available to you only if you mixed awk within your shell scripts (and hence the nickname K-shawk!). Here are some of the main ones:

  • Associative arrays. This is a big one. It helps you create associations (‘hashes’ in many languages) between strings. The traditional arrays can only use integers as indices, however, with associative arrays your can use strings as indices.

      $ typeset -A x=( [A]=1 [B]=2 )
      $ echo ${x[A]},${x[B]}
      1,2
    
  • Compound Variables. These are C-style structures that can be used to group multiple variables together and passed around to functions as parameters.

      $ typeset -C y=( A=1 B=2 )
      $ echo ${y.A},${y.B}
      1,2
    
  • Advanced Variable Substitution. You can perform substrings and string substitution within the variable substitution construct now.

      $ x=Hello
      $ echo ${x//Hell/Problem}
      Problemo
      $ echo ${x:0:4}
      Hell
    
  • New Date Capabilities. printf can now handle date time formatting and allows you to perform a lot of date calculations that were not possible without mixing some perl in your shell scripts.

      $ printf "%T\n" now
      Sat Aug 13 20:41:54 CDT 2016
      $ printf "%(%Y-%m-%d)T\n" now
      2016-08-13
    

There is a lot of depth to ksh93 and the more recent versions of the shell expand the compound variable syntax to provide object-oriented programming constructs and a lot more.
You can check what version comes with your OS distribution by running ksh93 --version or ksh --version (Most of the linux distributions will only have ksh93 and they link it as ksh).

Visit David Korn's website KornShell.com for more details.
Also, Musings of an OS Plumber has great tutorials on some advanced ksh93 features.

Manuj Bhatia

Manuj Bhatia