Class 5 of 37 • Linux Shell Essentials \t\t\t\t

Korn Shell (ksh) in Linux Programming

Introduction to Korn Shell (ksh)

 The KornShell (ksh) is a Unix command processor and programming language developed by David G. Korn at AT&T Bell Laboratories in the early 1980s and formally presented at the USENIX conference on July 14, 1983. Initial development was engineered directly on the Bourne shell source code.

 Prior to the KornShell, Unix users were divided between the Bourne Shell (superb for automation scripting, but clunky for interactive typing) and C Shell (convenient history and aliases, but riddled with scripting bugs). KornShell solved this dilemma by combining 100% backward compatibility with the Bourne Shell while implementing the best interactive features of C Shell, along with blazing performance improvements.

 Key contributors Mike Veach and Pat Sullivan implemented the world's first interactive command-line editing interfaces in a shell, allowing terminal users to navigate and edit their command line using either Emacs or VI keybindings.

Linux Shell Types Evolution Diagram

Figure 1: Evolution of KornShell (ksh88 / ksh93) bridging Bourne Shell and modern Bash


1. Major Innovations Introduced by KornShell

Many features now standardized in POSIX and GNU Bash were initially invented by David Korn for Ksh:

  • In-Line Command Line Editing: Users can toggle set -o vi or set -o emacs to edit command lines with cursor keys, search history, and delete words.
  • Native Arithmetic Evaluations: Built-in $(( ... )) expression syntax eliminated the need to spawn external expr or bc processes.
  • Modern Command Substitution: The nestable $(command) syntax was created in Ksh to replace fragile backticks `command`.
  • Associative Arrays & Types: Using typeset -A, Ksh introduced key-value dictionary mappings and typed variables (integers, uppercase, lowercase).
  • Coprocesses (|&): Allows a shell script to spawn a concurrent background process and communicate bidirectionally with it via print -p and read -p.
  • Extended Pattern Matching: Regex-like filename globs: ?(pattern), *(pattern), +(pattern), @(pattern), and !(pattern).

2. KornShell Script Syntax & Working Example

Here is a robust KornShell script checking for file existence and non-zero byte size using the POSIX/Ksh -s test operator:

#!/bin/ksh
# =========================================================
# Script: check_file.ksh
# Interpreter: Korn Shell (/bin/ksh or /bin/pdksh)
# Purpose: Verify file existence and non-empty content
# =========================================================

# Check if command-line argument was supplied
if [ -z "$1" ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi

# The -s flag tests if file exists AND has size greater than zero
if test ! -s "$1"; then
    echo "File '$1' does not exist or is empty (0 bytes)."
else
    echo "File '$1' verified: exists and contains data."
fi

Execution output:

$ chmod +x check_file.ksh
$ touch empty.txt
$ ./check_file.ksh empty.txt
File 'empty.txt' does not exist or is empty (0 bytes).

$ echo "Veewom Linux" > sample.txt
$ ./check_file.ksh sample.txt
File 'sample.txt' verified: exists and contains data.

3. Interactive In-Line Editing: VI and Emacs Modes

One of Ksh's greatest contributions is in-line editing. You can activate your preferred editor keys in any Ksh or Bash terminal session:

VI Mode: set -o vi
  • Press ESC to enter Command Mode
  • h, j, k, l to navigate left, down, up, right
  • /pattern to search reverse command history
  • dw to delete a word, x to delete character
  • i or a to return to Insert Mode
Emacs Mode: set -o emacs
  • Ctrl + A: Jump cursor to beginning of line
  • Ctrl + E: Jump cursor to end of line
  • Ctrl + R: Incremental reverse history search
  • Ctrl + K: Kill (delete) to the end of line
  • Ctrl + U: Discard whole input line

4. Technical Comparison: Korn Shell vs Bourne Shell vs Bash

Feature Bourne Shell (sh) Korn Shell (ksh93) GNU Bash
Bourne Compatibility Base standard 100% Compatible 100% Compatible
Floating Point Math No (external bc) Yes (built-in native math) No (integers only)
Associative Arrays None typeset -A declare -A (Bash 4.0+)
Line Editing Modes None VI & Emacs built-in GNU Readline (VI & Emacs)
Coprocess Support None Native with |& coproc keyword (Bash 4.0+)
Enterprise Dominance Legacy standard AIX, HP-UX, Solaris standard Linux default standard

5. The Versions of KornShell: ksh88, ksh93, and mksh

Across the history of computing, three major releases defined KornShell:

  • ksh88: Released in 1988, this landmark version became the formal blueprint for the POSIX.2 shell specification. It was the default enterprise shell for IBM AIX and HP-UX for decades.
  • ksh93: A ground-up rewrite in 1993 by David Korn adding native IEEE 754 floating-point calculations, compound variables, discipline functions (get/set triggers on variable access), and high-speed internal C function bindings.
  • mksh (MirBSD Korn Shell): The ultra-compact, actively maintained open-source successor. Notably, Google chose mksh as the official default shell in Android OS (inside /system/bin/sh).

6. Hands-on Lab Practice Drill

Lab Exercise: Associative Arrays & Math in KornShell

Create a script named ksh_features.ksh demonstrating associative arrays and arithmetic calculations:

$ cat << 'EOF' > ksh_features.ksh
#!/bin/ksh
# -------------------------------------------------------------
# File: ksh_features.ksh
# Purpose: Demonstrate ksh93 associative arrays and math
# -------------------------------------------------------------

# 1. Define an associative array
typeset -A inventory
inventory[laptops]=45
inventory[monitors]=120
inventory[servers]=8

# 2. Iterate through associative keys
echo "=== Warehouse Inventory ==="
for item in "${!inventory[@]}"; do
    echo "Item: $item | Stock: ${inventory[$item]}"
done

# 3. Native arithmetic calculation
total=$(( inventory[laptops] + inventory[monitors] + inventory[servers] ))
echo "Total Asset Count: $total"
EOF

$ chmod +x ksh_features.ksh
$ ./ksh_features.ksh
=== Warehouse Inventory ===
Item: laptops | Stock: 45
Item: monitors | Stock: 120
Item: servers | Stock: 8
Total Asset Count: 173

7. University Viva & Job Interview Q&A

Q1: What is a coprocess in KornShell and how is it started?

Answer: A coprocess is a background pipeline initiated with the |& operator. It runs asynchronously while allowing the parent script to write to its standard input using print -p and read from its standard output using read -p.

Q2: How does Ksh support floating point math while Bash does not?

Answer: David Korn integrated floating-point arithmetic directly into the ksh93 evaluation engine (using standard C double types). In Bash, the arithmetic evaluator $(( ... )) is strictly 64-bit integer based.

Q3: Which shell does Google Android use as its default CLI?

Answer: The Android operating system uses mksh (MirBSD Korn Shell) as its default command interpreter located at /system/bin/sh due to its tiny binary footprint and strict POSIX conformance.


8. Frequently Asked Questions (FAQ)

How do I install KornShell on Ubuntu or Debian?

You can install AT&T ksh93 or mksh using: sudo apt update && sudo apt install ksh mksh. Check your installation by running ksh --version.

Can I run Bash scripts in KornShell?

Most standard Bash scripts will run without issues in ksh93 because Bash adopted almost all of Ksh's features. However, Bash-specific built-ins or syntax like function foo() vs foo() may occasionally require adjustment.

Next Step in Your Linux Learning Path:

Master the ubiquitous GNU Bourne-Again Shell and its Readline power shortcuts in Class 6: Bash Shell.

Continue to Class 6: Bash Shell (bash) → Previous: ← C Shell | Full Syllabus

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!