Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

2.5 The Korn Shell Constructs

The Korn and Bash shells are very similar. The following constructs will work for both shells. To see all the subtle variations, see the individual chapters for these shells.

Table 2.3. Korn Shell Syntax and Constructs

The shbang line

The "shbang" line is the very first line of the script and lets the kernel know what shell will be interpreting the lines in the script. The shbang line consists of a #! followed by the full pathname to the shell, and can be followed by options to control the behavior of the shell.

EXAMPLE

#!/bin/ksh

Comments

Comments are descriptive material preceded by a # sign. They are in effect until the end of a line and can be started anywhere on the line.

EXAMPLE

# This program will test some files

Wildcards

There are some characters that are evaluated by the shell in a special way. They are called shell metacharacters or "wildcards." These characters are neither numbers nor letters. For example, the *, ?, and [ ] are used for filename expansion. The <, >, 2>, >>, and | symbols are used for standard I/O redirection and pipes. To prevent these characters from being interpreted by the shell they must be quoted.

EXAMPLE


rm *; ls ??; cat file[1-3];
echo "How are you?"

Displaying output

To print output to the screen, the echo command can be used. Wildcards must be escaped with either a backslash or matching quotes. Korn shell also provides a built-in print function to replace the echo command.

EXAMPLE


echo "Who are you?"
print "How are you?"

Local variables

Local variables are in scope for the current shell. When a script ends or the shell exits, they are no longer available; i.e., they go out of scope. The typeset built-in command can also be used to declare variables. Local variables are set and assigned values.

EXAMPLE


variable_name=value
typeset variable_name=value
name="John Doe"
x=5

Global variables

Global variables are called environment variables. They are set for the currently running shell and any process spawned from that shell. They go out of scope when the script ends or the shell where they were defined exits.

EXAMPLE


export VARIABLE_NAME =value
export PATH=/bin:/usr/bin:.

Extracting values from variables

To extract the value from variables, a dollar sign is used.

EXAMPLE


echo $variable_name
echo $name
echo $PATH

Reading user input

The user will be asked to enter input. The read command is used to accept a line of input. Multiple arguments to read will cause a line to be broken into words, and each word will be assigned to the named variable. The Korn shell allows the prompt and read command to be combined.

EXAMPLE

read name?"What is your name?"    The prompt is in quotes. After it is displayed,
the
read command waits for user input
print -n "What is your name?"
read name
read name1 name2 ...

Arguments

Arguments can be passed to a script from the command line. Positional parameters are used to receive their values from within the script.

EXAMPLE

At the command line:

$ scriptname arg1 arg2 arg3 ...

In a script:

echo $1 $2 $     Positional parameters, $1 is assigned arg1, $2 is assigned arg2, ...

echo $*                  All the positional paramters

echo $#                   The number of positional parameters

Arrays

The Bourne shell utilizes positional parameters to create a word list. In addition to positional parameters, the Korn shell also supports an array syntax whereby the elements are accessed with a subscript, starting at 0. Korn shell arrays are created with the set -A command.

EXAMPLE

set apples pears peaches                 Positional parameters
print $1 $2 $3                           $1 is apples, $2 is pears, $3 is peaches
set -A array_name word1 word2 word3 ...  Array 
set -A fruit apples pears plums
print ${fruit[0]}                        Prints apple
${fruit[1]} = oranges                    Assign a new value

Arithmetic

The Korn shell supports integer arithmetic.The typeset i command will declare an integer type variable. Integer arithmetic can be performed on variables declared this way. Otherwise, the (( )) syntax (let command) is used for arithmetic operations.

EXAMPLE

typeset -i variable_name       Declare integer
typeset -i num                 num is declared as an integer
num=5+4
print $num Prints 9
(( n=5 + 5 ))                  The let command
print $n Prints 10

Command substitution

Like the C/TC shells and the Bourne shell, the output of a UNIX/Linux command can be assigned to a variable, or used as the output of a command in a string, by enclosing the command in backquotes. The Korn shell also provides a new syntax. Instead of placing the command between backquotes, it is enclosed in a set of parentheses, preceded by a dollar sign.

EXAMPLE


variable_name=`command`
variable_name=$( command )
echo $variable_name

echo "Today is `date`"
echo "Today is $(date)"

Operators

The Korn shell uses the built-in test command operators to test numbers and strings, similar to C language operators.

EXAMPLE

Equality:

=      string, equal to
!=     string, not equal to
==     number, equal to
!=     number, not equal to

Relational:

>     greater than
>=     greater than, equal to
<     less than
<=     less than, equal to

Logical:

&&     and
||     Or
!      Not

Conditional statements

The if construct is followed by an expression enclosed in parentheses. The operators are similar to C operators. The then keyword is placed after the closing parenthesis. An if must end with a fi. The new test command [[ ]] is now used to allow pattern matching in conditional expressions. The old test command [ ] is still available for backward compatibility with the Bourne shell. The case command is an alternative to if/else.

EXAMPLE

The if construct is:

if command
then
   block of statements
fi
----------------------------
if [[ string expression ]]
then
   block of statements
fi

The if/else construct is:

if command
then
   block of statements
else
   block of statements
fi
--------------------------
if [[ expression ]]
then
   block of statements
else
   block of statements
fi
---------------------------
if (( numeric expression ))
then
   block of statements
else
   block of statements
fi
             

The case construct is:

case variable_name in
   pattern1)
      statements
         ;;
   pattern2)
      statements
         ;;
   pattern3)
         ;;
esac
-------------------------
case "$color" in
   blue)
      echo $color is blue
         ;;
   green)
      echo $color is green
         ;;
   red|orange)
      echo $color is red or orange
         ;;
esac
             
----------------------------
if (( numeric expression ))
then
   block of statements
fi

 


The if/else/else if construct is:


if command
then
   block of statements
elif command
then
   block of statements
elif command
then
   block of statements
else
   block of statements
fi
---------------------------
if [[ string expression ]]
then
   block of statements
elif [[ string expression ]]
then
   block of statements
elif [[ string expression ]]
then
   block of statements
else
   block of statements
fi
----------------------------
if (( numeric expression ))
then
   block of statements
elif (( numeric expression ))
then
   block of statements
elif (( numeric expression ))
then
   block of statements
else
   block of statements
fi

Loops

There are four types of loops: while, until, for, and select.

The while loop is followed by an expression enclosed in square brackets, a do keyword, a block of statements, and terminated with the done keyword. As long as the expression is true, the body of statements between do and done will be executed.

The until loop is just like the while loop, except the body of the loop will be executed as long as the expression is false.

The for loop is used to iterate through a list of words, processing a word and then shifting it off, to process the next word. When all words have been shifted from the list, it ends.

The select loop is used to provide a prompt (PS3 variable) and a menu of numbered items from which the user inputs a selection The input will be stored in the special built-in REPLY variable. The select loop is normally used with the case command.

The loop control commands are break and continue. The break command allows control to exit the loop before reaching the end of it; the continue command allows control to return to the looping expression before reaching the end.

EXAMPLE

while command
do
   block of statements
done
-----------------------------
while [[ string expression ]]
do
   block of statements
done
-----------------------------
while (( numeric expression ))
do
   block of statements
done


 
until command
do
    block of statements
done
-----------------------------
until [[ string expression ]]
do
    block of statements
done
-----------------------------
until (( numeric expression ))
do
    block of statements
done
          
for variable in word_list
do
   block of statements
done
-----------------------------
for name in Tom Dick Harry
do
   print "Hi $name"
done
   

select variable in word_list
do
   block of statements 
done 
-------------------------------
PS3="Select an item from the menu"
for item in blue red green
   echo $item
done
           
Shows menu:
  1. blue
  2. red
  3. green

File testing

The Korn shell uses the test command to evaluate conditional expressions and has a built-in set of options for testing attributes of files, such as whether it is a directory, a plain file (not a directory), a readable file, and so forth. See Example 2.5.

EXAMPLE

-d      File is a directory

-a      File exists and is not a directory

–r      Current user can read the file

–s      File is of nonzero size

–w      Current user can write to the file

–x      Current user can execute the file

Example 2.5.

  #!/bin/sh
1 if [ –a file ]
  then
       echo file exists
  fi
         
2 if [ –d file ]
  then
       echo file is a directory
  fi
      
3 if [ -s file ]
  then
       echo file is not of zero length
  fi
         
4 if [ -r file -a -w file ]
  then
       echo file is readable and writable
  fi

Functions

Functions allow you to define a section of shell code and give it a name. There are two formats: one from the Bourne shell, and the Korn shell version that uses the function keyword.

EXAMPLE


function_name() {
block of code
}

function function_name {
block of code
}
-------------------------
function lister {
echo Your present working directory is `pwd`
echo Your files are:
ls
}

2.5.1 The Korn Shell Script

Example 2.6.

1   #!/bin/ksh
2   # The Party Program––Invitations to friends from the "guest" file
   3   guestfile=~/shell/guests
   4   if [[ ! –a "$guestfile" ]]
   then
   print "${guestfile##*/} non–existent"
   exit 1
   fi
   5   export PLACE="Sarotini's"
   6   (( Time=$(date +%H) + 1 ))
   7   set -A foods cheese crackers shrimp drinks "hot dogs" sandwiches
   8   typeset -i n=0
   9   for person in $(< $guestfile)
   do
   10      if  [[ $person = root ]]
   then
   continue
   else
   # Start of here document
   11           mail –v –s "Party" $person <<- FINIS
   Hi ${person}! Please join me at $PLACE for a party!
   Meet me at $Time o'clock.
   I'll bring the ice cream. Would you please bring
   ${foods[$n]} and anything else you would like to eat? Let
   me know if you can make it.
   Hope to see you soon.
   Your pal,
   ellie@`hostname`
   FINIS
   12           n=n+1
   
   13           if (( ${#foods[*]} == $n ))
   then
   14             set -A foods cheese crackers shrimp drinks "hot dogs"
   sandwiches
   fi
   fi
   15  done
   print "Bye..."
   

EXPLANATION

  1. This line lets the kernel know that you are running a Korn shell script.

  2. This is a comment. It is ignored by the shell, but important for anyone trying to understand what the script is doing.

  3. The variable guestfile is set to the full pathname of a file called guests.

  4. This line reads: If the file guests does not exist, then print to the screen "guests nonexistent" and exit from the script.

  5. An environment variable is assigned a value and exported (made available to subshells).

  6. The output of the UNIX/Linux command, the hour of the day, is assigned to the variable called Time. Variables are assigned the values for the place and time.

  7. The list of foods to bring is assigned to an array called foods with the set –A command. Each item on the list can be accessed with an index starting at 0.

  8. The typeset –i command is used to create an integer value.

  9. For each person on the guest list a mail message will be created inviting the person to a party at a given place and time, and assigning a food from the list to bring.

  10. The condition tests for the user root. If the user is root, control will go back to the top of the loop and assign the next user in the guest list to the variable, person.

  11. The mail message is sent. The message body is contained in a here document.

  12. The variable n is incremented by 1.

  13. If the number of elements in the array is equal to the value of the variable, then the end of the array has been reached.

  14. This marks the end of the looping statements.

  • + Share This
  • 🔖 Save To Your Account