Week Three Tutorial Exercises

  1. Given the following program called mycp
    
    # Copy a file -- final version
    numargs=$#
    filelist=
    copylist=
    # Process the arguments, storing all but the last in filelist
    while [ "$#" -gt 1 ]
    do
        filelist="$filelist $1"
        shift
    done
    to="$1"
    # If less than two args, or if more than two args and last arg
    # is not a directory, then issue an error message
    if [ "$numargs" -lt 2 -o "$numargs" -gt 2 -a ! -d "$to" ]
    then
        echo "Usage: mycp filel file2"
        echo " mycp file(s) dir"
        exit 1
    fi
    # Sequence through each file in filelist
    for from in $filelist
    do
        # See if destination file is a directory
        if [ -d "$to" ]
        then
            tofile="$to/'basename $from'"
        else
            tofile="$to"
        fi
        # Add file to copylist if file doesn't already exist
        # or if user says it's okay to overwrite
        if [ -f "$tofile" ]
        then
            echo "$tofile already exists; overwrite (yes/no)? \c"
            read answer
    	if [ "$answer" = yes ]
    	then
    	    copylist="$copylist $from"
    	fi
        else
    	copylist="$copylist $from"
        fi
    done
    # Now do the copy -- first make sure there's something to copy
    if [ -n "$copylist" ]
    then
        cp $copylist $to
    fi
    
    1. Write a program called mymv that does with the mv command what the above program mycp does with the cp program.
    2. Modify the mycp program to prompt for arguments if none are supplied. A typical execution of the modified version should look like this.
      
                $ mycp
                Source filename? voucher
                Destination filename? voucher.sv
                $
      
      Be sure that the program allows one or both files to be specified with filename substitution characters.
    3. Add a -n option to mycp that supresses the normal check for the existence of the destination files. (Kochan and Wood P235)
  2. Here are two programs called prog1 and prog2:
    
                  $ cat prog1
                  e1=100
                  export e1
                  e2=200
                  e3=300
                  prog2
                  $ cat prog2
                  echo $e1 $e2 $e3 $e4
                  $
    
    What output would you expect after typing the following:
    
                  $ e2=20 ; export e2
                  $ e4=40 ; prog1
    
    (Kochan and Wood P272)