CS534 Lab 3: Linux/UNIX Shell Scripts

Please use the vi editor to create the scripts in this lab

To make life easier, create a Lab3 directory, and work on the scripts from there


Script #1

NOTE: If you can't execute the script, (and you are sure you don't have a typo), you might have to add the current directory to your path.

Check your path with echo $PATH and if "." is not in your path add it with export PATH=$PATH:. OR export PATH=$PATH:

Be sure that the working directory is NOT the first element in the path statement.


Script #2

Commands can be run from within your shell script. You can also access environment variables. For the second shell script enter the lines below. This shows how command substitution works. The output of the date and pwd commands are substituted into the strings being echoed.


Script #3

When passing arguments to a program or script, it is sometimes helpful to see what they are. The variables $1, $2, $3 , etc stand for the arguments passed to the script in order on the command line. $0 is the name of the command, script or program, $# is the number of parameters passed in, and $* and/or $@ list all the command line parameters. Consult your text for the differences between $* and $@.

Add an appropriate construct that will display a usage message if the correct number of arguments (3) aren't entered on the command line. Remember that arg(0) is not part of the total argument count.


Script #4

Background:
The shell variable $? provides the return code from the last command executed.
Run the following commands to see how it works:

Notice that when the command completed successfully the value of $? was 0

When there was an error, $? provided the error number

This return code can be used to put some error handling in a shell script. The backslash character ( \ ) is a continuation character. It must be the last character on that line, not even spaces are allowed after the continuation character


Script #5

	#!/bin/bash
	#
	# script5.bash
	#
	# An example with the case statement
	#
	# Reads a command from the user and processes it
	#
	echo -n "Enter your command from the following list (who, list, or cal) at the prompt: "
	read command
	case "$command" in
		who)
			echo "Running who..."
			who
			who > fivewho.out
			;;
		list)
			echo "Running ls..."
			ls
			ls > fivels.out
			;;
		cal)
			echo "Running cal..."
			cal
			cal > fivecal.out
			;;
		*)
			echo "Bad command, your choices are: who, list, or cal" > fivebadcommand.out
			;;
	esac
	exit 0


Script #6


Script #7

The while Statement


Script #8

Reading a File with a While Loop
		#!/bin/bash
		#
		# script8.bash
		#
		# Illustrates use of a while loop to read a file
		#
		# Use the line break to make code more readable
		cat microp.dat | \
		while read line
		do
			echo "Found line: $line"
		done
	


Script #9

Until loops


Script #10

for loops - part 1