Examples of Bourne shell scripts

To read input to a command and process it in some way:

   #!/bin/sh
   # usage: fsplit file1 file2
   total=0; lost=0
   while read next
   do
   total=`expr $total + 1`
   case "$next" in
   *[A-Za-z]*)  echo "$next" >> $1 ;;
   *[0-9]*)     echo "$next" >> $2 ;;
   *)           lost=`expr $lost + 1`
   esac
   done
   echo "$total lines read, $lost thrown away"

The user types the command:

   fsplit file1 file2

They then enter lines of text and issue an EOF instruction. The script then processes the lines as follows:

A line with at least one letter is appended to file1; any line with at least one digit and no letters is appended to file2. All other lines are thrown away.


To read commands from the terminal and process them:

   #!/bin/sh
   # usage: process sub-directory
   dir=`pwd`
   for i in *
   do
   if test -d $dir/$i
   then
     cd $dir/$i
     while echo "$i:" 
     read x
     do
       eval $x
     done
     cd ..
   fi
   done

The user types the command:

   process sub-directory

This script will read and process commands in the named sub-directory. The user is prompted to supply the name of the command to be read in. This command is executed using the the builtin eval function.


To create a command:

   #!/bin/sh
   flag=
   for i
   do
   case $i in
   -c)   flag=N ;;
    *)   if test -f $i
         then
           ln $i junk$$
           rm junk$$
         elif test $flag                 # true if not null
         then
           echo \'$i\' does not exist
         else
           >$i
         fi ;;
   esac
   done

This command takes filenames as its parameters. If a file exists it changes the modification date. If no file exists it creates a new one. This script is similar in action to the touch command.

The -c argument lets you specify that you only want to update a file that already exists and not to create one if it doesn't.


[Home] [Search] [Index] This site maintained by unixhelp@mathcs.duq.edu