Exercise: Write a simple shell script myscript.sh that takes a path of a directory as a command
line argument and list all files and folders inside the given directory. Run the script as:
sh myscript.sh /afs/andrew/course/15/123
If there are more than 9 command-line arguments, there is a bit of a problem -- there are only 9
positionals: $1, $2, ..., $9. $0 is special and is the shell script's name.
To address this problem, the shift command can be used. It shifts all of the arguments to the left,
throwing away $1. What would otherwise have been $10 becomes $9 -- and addressable. We'll
talk more about shift after we've talked about while loops.
Quotes, Quotes, and More Quotes
Shell scripting has three different styles of quoting -- each with a different meaning:
• unquoted strings are normally interpreted
• "quoted strings are basically literals -- but $variables are evaluated"
• 'quoted strings are absolutely literally interpreted'
• `commands in quotes like this are executed, their output is then inserted as if it were
assigned to a variable and then that variable was evaluated`
"quotes" and 'quotes' are pretty straight-forward -- and will be constantly reinforced. But,
Here is an example using `quotes` - commands in quotes
day=`date | cut -d" " -f1`
printf "Today is %s.\n" $day
The first expression finds the current date and uses cut (string tokenizer) to extract a specific part
of the date. Then it assigns that to variable day. The day then is used by printf statement. You
can read more about cut command later in this lecture. Cut comes handy in many shell scripts as
it allows us to look at a specific token of a string.
Evaluating Expr
Shell scripts are not intended to do complex mathematical expressions. But expr program can be
used to manipulate variables, normally interpreted as strings, as
integers. Consider the following "adder" script:
sum=`expr $1 + $2`
printf "%s + %s = %s\n" $1 $2 $sum
A Few Other Special Variables
We'll talk a bit more about these as we get into more complex examples. For now, I'd just like to
mention them:
• $? - the exit status of the last program to exit
• $$ - The shell's pid
Predicates
The convention among UNIX programmers is that programs should return a 0 upon success.
Typically a non-0 value indicates that the program couldn't do what was requested. Some (but