Script Execution and Arguments



next up previous contents index
Next: Loop through Arguments: Up: Shell Programs (Scripts) Previous: Shell Programs (Scripts)

Script Execution and Arguments

For our first try we created a shell script in the file try:


#!/bin/sh sh shell's file try. echo "The number of arguments is $#" echo "They are $*" echo "The first is $1" echo "The number of arguments is $#" exit

You will want to try this and the following scripts out on your system. Because scripts are ordinary text files, you may use your favorite editor to create them. To start, notice that the first line is #!/bin/sh. This tells Unix to use the Borne or sh shell. This is interesting since any line beginning with a # is usually a comment, but the combination #! is special. It says that this file should be interpreted using the program that follows. In this case it is /bin/sh, although /bin/ksh is also possible. This must be the first line of the file, and in fact, #! must be the first two characters. Traditionally, shell scripts that don't start with #! are assumed to be Borne shell scripts, but since this convention is broken by some newer systems, it is always a good idea to declare what shell you want.

Some lines in the script have the form echo "$1". This command echoes, that is, prints on your screen, the first argument given to the script when it is executed. Similarly, $2 is the second argument, $3 the third, and so on. Two special variables are also useful. The variable $* stands for all the arguments, and the variable $# for the number of arguments.

After the file try has been created using the editor, we make it executable:

% chmod +x try   	Make file try executable.   
% ls -l try   	Check for x rating.   
-rwxr-xr-x  1 pfink   usr    96 Nov 25 22:04 try   	   
% try red blue green   	Run the script in try.   
The number of arguments is 3   	   
They are red blue green   	   
The first is red   	   



next up previous contents index
Next: Loop through Arguments: Up: Shell Programs (Scripts) Previous: Shell Programs (Scripts)