CSE 374, Lecture 5: Shell Scripts

Exit codes

We use the command "exit" to quit an ssh session ("logging off") or to quit a shell script (end the program). "exit" also has an optional "error code" that you can provide to it to indicate whether or not the program ran successfully. An exit code of "0" indicates no errors (and is the default).

    # Both of the following exit statements do the same thing - indicates no error
    exit
    exit 0

On the other hand, "1" indicates a general error of some kind. So if we add a value of 1 in the case of something going wrong (like not enough arguments), we will indicate that things failed.

    exit 1

There are other codes that are conventionally used for certain kinds of errors - investigate on your own to see what those are and what they mean.

Comparison with Java

Scripting: general rules of thumb

Script: Safe Delete

Today, we'll review what we've learned about scripting to write a program "sdel" that safely deletes a file. This is similar to how the "Trash" works on a normal GUI operating system - when you delete a file, the file is not actually deleted but is instead moved to a folder called "TRASH". After a certain period of time in the TRASH (let's say 2 days), the files are then permanently deleted. In addition, we will compress the files using a utility called "tar" before putting them in the trash to save space.

First, we need to see whether the TRASH folder actually exists. Let's put the TRASH in the user's home directory.

    #!/bin/bash
    trash=~/TRASH
    if [ ! -e $trash ]; then
      mkdir $trash
    elif [ ! -d $trash ]; then
      echo "usage: trash is not a directory"; exit 1
      exit 1
    fi

Here we're using a few new ideas:

Now we want to go through the files given to the sdel command, tar them up, move the tar to the TRASH directory, and delete the original file.

    while [ $# -gt 0 ]; do
      if [ ! -e $1 ]; then
          echo "tried to delete file that does not exist:" $1; shift; continue
      fi
      tarname="$1.tar"
      tar -cf "$tarname" "$1"
      mv "$tarname" $trash
      rm -rf "$1"
      shift
    done

Note a few things we're using in this piece:

The final piece is to delete any files older than 2 days from the TRASH directory.

    now=`date +%s`
    cd $trash
    for f in `ls`; do
      fileage=$(stat -c '%Y' "$f")
      if [ $((now - fileage)) -gt $((60*60*24*2)) ]; then
        rm -rf "$f"
      fi
    done

What to note in this bit of code:

Last note

All of this work that we've been doin with scripts is NOT the same as the "script" command! The script command is misnamed; you've been using it to record your shell session in a file, but you can't actually run the resulting file. The "script" command is very different from the runnable scripts that we have been writing.