Complete KornShell (ksh) Cheatsheet

Powerful scripting and command-line features

Quick Reference

KornShell (ksh) is a Unix shell developed by David Korn at Bell Labs, combining features of Bourne shell and C shell.

cd
Change directory
cd /usr/local # Change to /usr/local
cd ~ # Change to home directory
cd - # Switch to previous directory
dirs
Show directory stack (ksh93+)
dirs # Show directory stack
dirs -v # Show with numbers
pushd, popd
Manipulate directory stack (ksh93+)
pushd /usr/local # Add to stack and cd
pushd +1 # Rotate stack
popd # Return to previous directory
pwd -P
Print physical directory (without symlinks)
pwd -P # Show actual path
pwd -L # Show with symlinks (default)

2 Variables

variable=value
Set shell variables
name="John"
count=10
files=$(ls) # Command substitution
export
Set environment variables
export PATH="/usr/local/bin:$PATH"
export EDITOR=vim
export -p # List all exported variables
unset
Remove variables
unset name # Remove variable
unset -f function_name # Remove function
Special variables
Predefined shell variables
$HOME # Home directory
$PATH # Executable search path
$? # Exit status of last command
$$ # Current process ID
$# # Number of arguments
$0 # Script name
Variable expansion
Advanced variable manipulation
${var:-default} # Use default if unset
${var#prefix} # Remove prefix
${var%suffix} # Remove suffix
${var//old/new} # Replace all occurrences
typeset
Declare variable attributes
typeset -i count # Integer variable
typeset -r PI=3.14 # Read-only variable
typeset -x VAR # Export variable
typeset -f # List functions

3 Arrays

set -A
Create indexed array (ksh88)
set -A colors red green blue
echo ${colors[1]} # green
array=(...)
Create indexed array (ksh93+)
colors=(red green blue)
files=(*.txt) # All .txt files
Associative arrays
Key-value pairs (ksh93+)
typeset -A person
person[name]="John"
person[age]=30
echo ${person[name]} # John
Array operations
Working with array elements
${array[*]} # All elements
${#array[*]} # Number of elements
${!array[*]} # All indices/keys
${array[@]:1:2} # Slice (elements 1-2)
Compound variables
Complex data structures (ksh93+)
typeset -C point=(x=10 y=20)
echo $point.x # 10
point.z=30 # Add new field

4 History

history
View command history
history # Show all commands
history 10 # Show last 10 commands
fc -l # Alternative to history
!! and !-n
Re-execute previous commands
!! # Repeat last command
!-2 # Repeat command 2 back
!string # Last command starting with 'string'
fc
Fix command (edit and re-run)
fc # Edit last command in $EDITOR
fc -l 100 105 # List commands 100-105
fc -s old=new # Substitute in last command
HISTFILE and HISTSIZE
Configure history behavior
HISTFILE=~/.ksh_history
HISTSIZE=1000
HISTCONTROL=ignoredups # Ignore duplicates
r
Repeat command (ksh93+)
r # Repeat last command
r vi # Repeat last vi command
r -2 # Repeat command 2 back

5 Job Control

jobs
List background jobs
jobs # List jobs
jobs -l # List with PIDs
&, bg, fg
Background and foreground jobs
long_command & # Run in background
Ctrl+Z # Suspend current job
bg %1 # Resume job 1 in background
fg %2 # Bring job 2 to foreground
kill
Terminate processes
kill %1 # Kill job 1
kill -9 1234 # Force kill PID 1234
kill -l # List signals
disown
Remove job from shell's job table
disown %1 # Remove job 1
disown -a # Remove all jobs

6 Scripting

Shebang
Ksh script header
#!/bin/ksh
#!/usr/bin/env ksh
Conditionals
If-then-else statements
if [[ $user == "root" ]]; then
  echo "You are root"
elif [[ $user == "admin" ]]; then
  echo "You are admin"
else
  echo "You are $user"
fi
Loops
For and while loops
# For loop
for color in red green blue; do
  echo $color
done

# While loop
count=1
while (( count <= 5 )); do
  echo "Count: $count"
  (( count++ ))
done
Case statement
Pattern matching conditional
case $choice in
  start)
    echo "Starting..."
    ;;
  stop)
    echo "Stopping..."
    ;;
  *)
    echo "Unknown option"
    ;;
esac
Functions
Define reusable code blocks
function greet {
  echo "Hello, $1"
}
greet "World" # Hello, World
Arithmetic
Numeric operations
(( sum = 5 + 3 ))
(( count++ ))
(( result = (x * y) / z ))
echo "Sum is $sum"
Command line args
Handling script arguments
# script.ksh arg1 arg2
echo "Script: $0"
echo "First arg: $1"
echo "All args: $@"
echo "Arg count: $#"
getopts
Process command-line options
while getopts ":a:b:" opt; do
  case $opt in
    a) arg_a=$OPTARG;;
    b) arg_b=$OPTARG;;
    \?) echo "Invalid option: -$OPTARG";;
  esac
done

7 Keyboard Shortcuts

Editing shortcuts
Command line editing
Ctrl+A # Move to beginning of line
Ctrl+E # Move to end of line
Ctrl+K # Delete to end of line
Ctrl+U # Delete to beginning of line
Ctrl+W # Delete previous word
Completion
File and command completion
Esc, Esc # Complete filename
Ctrl+D # List possible completions
Tab # Complete command (if set)
History navigation
Browse command history
Up/Down # Navigate history
Ctrl+P # Previous command
Ctrl+N # Next command
Ctrl+R # Reverse search
Process control
Manage running processes
Ctrl+C # Interrupt process
Ctrl+Z # Suspend process
Ctrl+D # End of input (logout)
Ctrl+S # Pause output
Ctrl+Q # Resume output