Putting it all together in a script

The following example shows a simple shell script that illustrates the features of the shell interpreter and utilities. The script takes one input parameter that is the name of a directory. The script then copies all of the files with the .java extension from the input directory to the current directory, keeping a count of the files it copied.

 1	# Get a list of files
 2	filelist=$(ls ${1}/*.java)
 3	count=0
 4	# Process each file
 5	for file in $filelist ; do
 6	  # Strip directory name
 7	  target=${file##*/}
 8	  # Copy file to current directory
 9	  cp $file $target
10	  count=$((count+=1))
11	  # Print message
12	  print Copied $file to $target
13	done
14	print Copied $count files

On lines 1, 4, 6 ,8, 11, the # character denotes a comment. Any characters after the # character are not interpreted by qsh.

On line 2, the variable filelist is set to the output from the ls command. The ${1} expands to the first input parameter and the *.java expands to all of the files with the .java extension.

On line 3, the variable count is set to zero.

On line 5 is a for loop. For each iteration of the loop. the variable file is set to the next element in the variable filelist. Each element is delimited by a field separator. The default field separators are tab, space, and newline. The semicolon character is a command delimiter and allows you to put more than one command on a line.

On line 7, the variable target is set to the file name from the fully-qualified path name. The ${file##*/} parameter expansion removes the largest pattern starting from the left that matches all characters up to the last slash character.

On line 9, the file is copied with the cp utility from the specified directory to the current working directory.

On line 10, the variable count is incremented by one.

On line 12, a message is printed using the print utility with the files that were copied.

On line 13, the done marks the end of the for loop.

On line 14, a message is printed with the total number of files that were copied.

If the directory /project/src contained two files with the .java extension and the script is called using the command:

javacopy /project/src

then the output from the script is

Copied /project/src/foo.java to foo.java
Copied /project/src/bar.java to bar.java
Copied 2 files