Up to main menu         Back to Graphics formats; PNG and JPG         Next: Read/Write/Execute Permissions

Shell Scripts

The simplest shell script is a text file which contains a series of Unix commands, one per line. If the file is made executable (chmod +x filename) then you need only type the name of the file for all the commands within to be executed, in order. Normally, however, you want to state explicitly the name of the shell which should interpret the commands, and for shell scripts this is the Bourne shell, sh. As the very top line of the shell script insert
#!/bin/sh
A simple useful shell script might be used to edit a Fortran program, compile it, run it, and look at the output:
             executable file "doit"
#!/bin/sh
xedit myprogram.f90
f90 -o myprog myprogram
./myprog > output.txt
more ./output.txt

Here is a (Bourne) shell script which shows some of the more advanced possibilities.
#!/bin/sh
#
#  Built-in variables for a Bourne shell script:
#
#	$#  -- number of arguments
#	$1, $2, ...  -- argument #1, #2, etc.
#	$*  -- all the arguments
#	$?  -- return value of last command executed
#
#	IF (numerical comparison) / THEN / ELSE
if [ $# -eq 2 ]
then
	echo 'you supplied this script with 2 parameters'
else
	echo "you did not supply this script with 2 parameters;"
	echo "you supplied it with $# parameters."
fi
#
#
#	HOW SCRIPT CAN PROMPT FOR & GET INPUT
echo -n 'Your name:  '
read YourName
#
#
#	STRING COMPARISON
if [ "$YourName" = "" ]
then
   echo 'You didn't type anything!'
   echo 'I quit.'
   exit 0
fi
#
#	SWITCHING TO MULTIPLE CASES
case $YourName in
x)	echo 'You only typed the letter "x".'    ;;
[sS]*)	echo 'Your name begins with the letter "S"' ;;
[gG]*)	echo 'Your name begins with the letter "G"' ;;
[qQ]*)	echo 'Your name begins with "Q"'
	echo '   ---   and I quit!'
	exit 0 ;;
*)	echo 'Interesting name.' ;;	# everything else
esac
#
#
#	RUN THROUGH FILE NAMES: LOOK FOR "diagonal matrix"
for filename in *
do
   echo "another file in this directory is $filename"
   grep -i "diagonal matrix" $filename
done
#
#
#	RUN THROUGH GIVEN LIST
#
for name in Rosa Samantha Tracy
do
   echo "I love $name"
done
#

Up to main menu         Back to Graphics formats; PNG and JPG         Next: Read/Write/Execute Permissions
Bruce.Fast@Colorado.EDU