ksh, csh, sh,
...) provides mechanisms for control (e.g., statements like
if, while, for, ...).
ksh information.
$ sh MyScript
$ csh MyOtherScript
$ ksh MyThirdScript
MyScript".
#!/usr/local/bin/ksh
(You could specify any command after "#!" to act as the
"interpreter" for the commands in the script, and you can
also give arguments.)
chmod to make it executable
(recall general formatchmod [ugoa][+-][rwx] filename"):
$ chmod a+x MyScript
MyScript like a regular
command:
$ MyScript
vi):
$ cat > gohome
#!/usr/local/bin/ksh
cd ~
ls -F
^D
$ chmod a+x gohome
$ gohome
[A-Za-z][A-Za-z0-9_]*.
ksh:
variable=value
export variable=value
export makes the value visible to
child processes.
$ person=Terry
$ echo person
person
$ echo $person
Terry
$ unset person
This is not the same as "person=''", which leaves the
variable defined, but with the null value.
print" or "echo":
$ print "Hello World"
Hello World
return N" to
give a specific return value, as in this script:
#!/usr/local/bin/ksh
print "Hello World"
return 0
$? to access
the exit status of the previously run command. If the above
script were HelloScript:
$ HelloScript
$ print $?
0
if condition
then
statements
[elif condition
then
statements]
[else
statements]
fi
then/else/elif/fi keywords take the place
of braces ({})---braces mean something special to the shell!
integer a
b):
(( a == 10 ))
(( b < 20 ))
[[ $person = steve ]]
[[ $person != todd ]]
(( (a < 10) || (a > 100) ))
[[ ($person != steve ) && ($person != todd ) ]]
elif or else parts can be omitted.
if [[ $person = steve ]]
then
print $person is on the sixth floor.
elif [[ $person = todd ]]
then
print $person is on the fifth floor.
elif [[ $person = markus ]]
then
print $person is on the fifth floor.
else
print "Who are you talking about?"
fi
while condition
do
statements
done
break or continue
or return inside a loop with the same meaning as in C.
#!/usr/local/bin/ksh
# Report type of executable file anywhere in search path.
#
path=$PATH
dir=${path%%:*}
while [[ -n $path ]]; do
if [[ -x $dir/$1 && ! -d $dir/$1 ]]; then
file $dir/$1
return
fi
path=${path#*:}
dir=${path%%:*}
done
print "File not found."
return 1
case expression in
pattern1 )
statements ;;
pattern2 )
statements ;;
.
.
.
esac
(pattern).
case $person in
steve)
print "He's on the sixth floor." ;;
todd | markus)
print "He's on the fifth floor." ;;
*)
print I do not know $person. ;;
esac
for loop can be used to iterate over all items in
an array or list.
for var [in list]
do
statements
done
in list is omitted in a script, the list is assumed
to be $* --- all the arguments to the script.
for name in Jack Jill John Jane Dick
do
print "Next person is $name."
done
integer count=0
for arg in $@
do
let count='count+1'
print "argument $count: $arg"
done
for i in *.for
do
mv $i ${i%.for}.f
print ${i%.for}.f
done