One Pager – Korn Shell A to Z

 

Ksh is a command and programming language that executes commands read from a terminal or a file.

 

BASICS
$ cd ~user1
Go to user’s home dir
$ cd ~
Go to home dir
$ cd –
Go to previous dir
EDITING
$ VISUAL=$(whence vi)
set -o vi
Set editing mode to vi
HISTFILE=~/.hist$$
history file
cleanup history files
0 2 * * * rm ~/.hist*
 DEL
Delete previous character
CTRL-W
Erase previous word
CTRL-V
Quote” the next character
ESC
Enter control mode
 h
Move left one character
l
Move right one character
w
Move right one word
b
Move left one word
W
Move to beginning of next non-blank word
B
Move to beginning of preceding non-blank word
e
Move to end of current word
E
Move to end of current non-blank word
0
Move to beginning of line
^
Move to first non-blank character in line
$
Move to end of line
i
Insert text before current character (insert)
a
Insert text after current character (append)
I
Insert text at beginning of the line
A
Insert text at end of the line
R
Overwrite existing text
dh
Delete one character backwards
dl
Delete one character forwards
db
Delete one word backwards
dw
Delete one word forwards
dB
Delete one non-blank word backwards
dW
Delete one non-blank word forwards
d$
Delete to end of line
d0
Delete to beginning of line
D
Same as d$ (delete to end of line)
dd
Same as 0d$ (delete entire line)
C
Same as c$ (delete to end of line, enter input mode)
cc
Same as 0c$ (delete entire line, enter input mode)
X
Same as dh (delete character backwards)
x
Same as dl (delete character forwards
k or –
Move backward one line
j or +
Move forward one line
G
Move to line given by repeat count
EDITING IN HISTORY MODE
? str
Search backward for string
/ str
Search forward for string
n
Repeat search in same direction as previous
N
Repeat search in opposite direction of previous
/^ma
Search for line that starts with ma (more file)
fx
Move right to next occurrence of x
Fx
Move left to previous occurrence of x
tx
Move right to next occurrence of x, then back one space
Tx
Move left to previous occurrence of x, then forward one space
;
Redo last character-finding command
,
Redo last character-finding command in opposite direction
FILE NAME COMPLETION
ESC ESC
ESC \
ESC *
ESC =
GOOD TO KNOW
~
Invert case of current character
Append last word of previous command, enter input mode.
v
Run the fc command on the current line
CTRL-L
Redraw editor
#
Prepend # (comment character)
@x
Insert expansion of alias _x
fc -l
list command history
r = fc -e
repeat last ran command (- old=new)
CUSTOMIZING ENVIRONMENT
.profile
Profile file
bgnice
Run background jobs at lower priority (on by default)
emacs
Enter emacs editing mode
ignoreeof
Don’t allow use of CTRL-D to log off; require the exit command
markdirs
When expanding filename wildcards, append a slash (/) to directories
noclobber
Don’t allow output redirection (>) to clobber an existing file
noglob
Don’t expand filename wildcards like * and ? [globbing]
nounset
Indicate an error when trying to use a variable that is undefined
vi
Enter vi editing mode
Set option
+
Unset option
unset
Delete variable
print [echo]
echo
~a and $
evaluated within “”
ENVIRONMENT VARIABLES
COLUMNS
Width, in character columns, of your terminal.
The standard value is 80 (sometimes 132), though if you are using a windowing system like X, you could give a terminal window any size you wish.
LINES
Length of your terminal in text lines.
HISTFILE
Name of history file
EDITOR
text editor
VISUAL
Similar to EDITOR
FCEDIT
Pathname of editor to use with the fc command.
MAIL
Name of file to check for incoming mail (i.e., your mail file)
MAILCHECK
How often, in seconds, to check for new mail (default 600 seconds, or 10 minutes)
MAILPATH
List of filenames, separated by colons (:), to check for incoming mail
LOGNAME
variable set to your login name
!
command number
PS1='($PWD)->’
set primary prompt to current directory
/usr/lib/terminfo
terminal definitions
PATH=$PATH”:/home/you/bin”
Path to executable files
CDPATH
list of directories that cd with use to search for sub directory
varname=value command
example:
LD_PATH=/home/mylib ./home/script/runme.sh
Variable to be in the environment of a particular subprocess
PS3
The prompt string that select flow command uses as prompt.
FUNCTIONS
function functname {
     shell commands
}
or
functname () {
     shell commands
}
returnN
exitN
#exit function and return status N
#exit script and return status N
unset -f functname
free up memory from function
functions
See definded functions
FPATH
Path to look for functions to autoload at execution time
autoload function_name
Load function at execution time
$ whence -v cd
cd is a shell builtin
POSITIONAL PARAMETERS
$0
$1
$2
$#
name of the script being executed
first parameter
second parameter
number of positional parameters
$*
is a single string that consists of all of the positional parameters, separated by the first character in the environment variable IFS (internal field separator)
$@
is equal to “$1″”$2″…”$N”, separated by double-quotes and space
VARIABLE
${varname}
It is safe to omit the curly brackets ({}) if the variable name is followed by a character that isn\’t a letter, digit, or underscore.
SUBSTITUTION OPERATORS
${varname :- word}
Example:
${count:-0}
Evaluates to 0 if count is undefined.
If varname exists and isn’t null, return its value.
Otherwise return word.
#
Purpose:
Returning a default value if the variable is undefined.
${varname := word}
Example:
${count:=0}
Set count to 0 if it is undefined.
If varname exists and isn’t null, return its value otherwise set it to word and then return its value.
#
Purpose:
Setting a variable to a default value if it is undefined.
${varname 😕 message}
Example:
{count :?”undefined!”}
Prints “count: undefined!” and exits if count is undefined.
If varname exists and isn’t null, return its value.
Otherwise print “varname: followed by message”, and abort the current command or script.
Omitting message produces the default message parameter null or not set.
#
Purpose:
Catching errors that result from variables being undefined.
${varname :+ word}
Example:
${count:+1}
returns 1 (which could mean “true”) if count is defined.
If varname exists and isn’t null, return word; otherwise return null.
#
Purpose:
Testing for the existence of a variable.
REGULAR EXPRESSION OPERATORS
*(exp)
0 or more occurrences of exp; in awk exp*
+(exp)
1 or more occurrences of exp; in awk exp+
?(exp)
0 or 1 occurrences of exp; in awk exp ?
@(exp1|exp2|…)
exp1 or exp2 or…; in awk exp1|exp2|..
!(exp)
Anything that doesn’t match exp[8]; in awk (none)
PATTERN MATCHING
${variable#pattern}
If the pattern matches the beginning of the variable’s value, delete the shortest part that matches and return the rest.
${variable##pattern}
If the pattern matches the beginning of the variable’s value, delete the longest part that matches and return the rest.
${variable%pattern}
If the pattern matches the end of the variable’s value, delete the shortest part that matches and return the rest.
${variable%%pattern}
If the pattern matches the end of the variable’s value, delete the longest part that matches and return the rest.
example:
${name##*/}
${#varname}
#
#
# equivalent to basename command
# length of the value of the variable
COMMAND SUBSTITUTION
$(unix_command)
execute command within brackets and return the value to standard output.
Example:
ls -l $(whence -p command)
#  Find info about command
Example:
varname=$(<filename)
# Get a content of a file into a variable.
Example:
varname=$(cat filename)
# Same as above but slower
Example:
PS1=”$(hostname) \$ “
# Set default prompt.
popd 
pushd
# add directory to the end directory stack
# remove last added directory from the directory stack
example:
init state
pushd newdir
pushd /etc
popd
popd
popd

#

/home/myhome [stack];/home/myhome [dir]
/home/myhome,/home/myhome/newdir [stack]; /home/myhome/newdir [dir]
/home/myhome,/home/myhome/newdir,/etc [stack]; /etc [dir]
/home/myhome,/home/myhome/newdir [stack]; /home/myhome/newdir [dir]
/home/myhome [stack];/home/myhome [dir]
empty [stack];ERROR [dir]
Example:
#Push current directory onto stack
function pushd {
    dirname=$1
    cd ${dirname:?”missing directory!”}
    DIRS=”$dirname ${DIRS:-$PWD}”
    print “$DIRSTACK”
}
#Pop directory off stack, cd to new top
function popd {
    DIRS=${DIRS#* }
    cd ${DIRS%% *}
    print “$PWD”
}
FLOW CONTROL
if condition
then
     statements
[elif condition
then statements…]
[else statements]
fi
or:
if [[ condition ]]; then
     else
fi
Two statements test:
if statement1 && statement2
then
     statements
fi
or:
if statement1 || statement2
then
     …
fi
IF/ELSE
for name [in list]
do
     statements that can use $name…
done
FOR
Example:
dos_regexp='[^a-z]\{1,8\}\.[^a-z]\{0,3\}’
for filename in ${1:+$1/}* ; do
     if print $filename | grep $dos_regexp > /dev/null; then
          newfilename=$(print $filename | tr [A-Z] [a-z])
          newfilename=${newfilename%.}
          print “$filename -> $newfilename”
          mv $filename $newfilename
     fi
done
#
#convert dos names to unix
case expression in
     pattern1 )
          statements ;;
     pattern2 )
          statements ;;
     …
esac
CASE
Example:
case $(tty) in
     /dev/tty0[134] ) TERM=gl35a ;;
     /dev/tty07 ) TERM=t2000 ;;
     /dev/tty08 | /dev/console ) TERM=s531 ;;
     * ) TERM=vt99 ;;
esac
#
#select terminal type
select name [in list]
do
     statements that can use $name…
done
SELECT
Example:
PS3=’terminal? ‘
select term in gl35a t2000 s531 vt99; do
     if [[ -n $term ]]; then
          TERM=$term
          print TERM is $TERM
          break
     else
          print ‘invalid.’
     fi
done
#
#select terminal type
break
BREAK – exits to select loop
while condition
do
     statements…
done
WHILE
#In while, the loop executes as long as the condition is true
Example:
path=$PATH:
dir=${path%%:*}
while [[ -n $path ]]; do
     if [[ -x $dir/$1 && ! -d $dir/$1 ]]; then
          print “$dir/$1”
          return
     fi
     path=${path#*:}
     dir=${path%%:*}
done
return 1
#
while iterative-step; condition; do
done
UNTIL
#in until, it runs as long as the condition is false.
Example:
path=$PATH
while dir=${path%%:*}; [[ -n $path ]]; do
     if [[ -x $dir/$1 && ! -d $dir/$1 ]]; then
          file $dir/$1
          return
     fi
     path=${path#*:}
done
return 1
STRING COMPARISON
str = pat
str matches pat.
str != pat
str does not match pat.
str1 < str2
str1 is less than str2.
str1 > str2
str1 is greater than str2.
-n str
str is not null (has length greater than 0).
-z str
str is null (has length 0).
Example:
function popd {
if [[ -n $DIRSTACK ]]; then
     DIRSTACK=${DIRSTACK#* }
     cd ${DIRSTACK%% *}
     print “$PWD”
else
     print “stack empty, still in $PWD.”
fi
}
#
# pop directory off the stack, cd there
Example:
if [[ -z $1 ]]; then
     print ‘usage: howmany filename [-N]’
     return 1
fi
filename=$1
howmany=${2:-10}
sort -nr $filename | head -$howmany
#
#List only this lines from the files
FILE OPERATORS
-a file
file exists
-d file
file is a directory
-f file
file is a regular file
-r file
You have read permission on file
-s file
exists and is not empty
-w file
You have write permission on file
-x file
You have execute permission on file, or directory search perm.
-O file
You own file
-G file
Your group ID is the same as that of file
file1 -nt file2
file1 is newer than file2
file1 -ot file2
file1 is older than file2
Example:
# push current directory onto stack
function pushd {
dirname=$1
if [[ -d $dirname && -x $dirname ]]; then
     cd $dirname
     DIRSTACK=”$dirname ${DIRSTACK:-$PWD}”
     print “$DIRSTACK”
else
     print “still in $PWD.”
fi
}
ARITMETICS OPERATORS
-lt
Less than
-le
Less than or equal
-eq
Equal
-ge
Greater than or equal
-gt
Greater than
-ne
Not equal
COMMAND LINE OPTIONS AND TYPED VARIABLES
1=$2
2=$3
shift
Example:
while [[ $1 = -* ]]; do
     case $1 in
          -a ) process option -a ;;
          -b ) process option -b ;;
          -c ) process option -c ;;
          *  ) print ‘usage: bob [-a] [-b] [-c] args…’
          return 1
     esac
     shift
done
normal processing of arguments…
case and CLI options
Example:
while [[ $1 = -* ]]; do
     case $1 in
          -a ) process option -a ;;
          -b ) process option -b
               $2 is the option’s argument
               shift ;;
          -c ) process option -c ;;
          *  ) print ‘usage: bob [-a] [-b barg] [-c] args…’
                return 1
     esac
     shift
done
normal processing of arguments…
case and CLI options with args
Example:
while getopts “:ab:c” opt; do
     case $opt in
          a ) process option -a ;;
          b ) process option -b
               $OPTARG is the option’s argument ;;
          c ) process option -c ;;
          \? ) print ‘usage: bob [-a] [-b barg] [-c] args…’
               return 1
     esac
done
shift $(($OPTIND – 1))
normal processing of arguments…
Example:
while getopts “:cgl:o:O” opt; do
     case $opt in
          c ) do_link=false ;;
          g ) debug=”-g” ;;
          l ) link_libs=”$link_libs -l $OPTARG” ;;
          o ) exefile=”-o $OPTARG” ;;
          O ) opt=true ;;
          \? ) print ‘usage: occ [-cgO] [-l lib] [-o file] files…’
          return 1 ;;
     esac
done
shift $(($OPTIND – 1))
getopts
getopts takes two arguments.
The first is a string that can contain letters and colons.
Each letter is a valid option; if a letter is followed by a colon, the option requires an argument.
INTEGER VARIABLES AND ARITHMETICS
+
*
/
%
Remainder
<<
Bit-shift left
>>
Bit-shift right
&
Bitwise and
!
Bitwise or
~
Bitwise not
^
Bitwise exclusive or
Example:
print “Only $(( 365-$(date +%j) )) days until the New Year!”
RELATIONAL OPERATORS
<
Less than
>
Greater than
<=
Less than or equal
>=
Greater than or equal
=
Equal
!=
Not equal
&&
Logical and
||
Logical or
((…))
evaluating arithmetic condition
(( intvar=expression ))
let intvar=expression

Reference:

man ksh

Learning_the_Korn_Shell [Buy the book and support this great read].

 

One thought on “One Pager – Korn Shell A to Z

Leave a Reply

Your email address will not be published. Required fields are marked *