- Taking a Peek at Shell Scripts
- Sample Scripts: Comparing the Major Shells
- The C and TC Shell Syntax and Constructs
- The Bourne Shell Syntax and Constructs
- The Korn Shell Constructs
- The Bash Shell Constructs
2.3 The C and TC Shell Syntax and Constructs
The basic C and TC shell syntax and constructs are listed in Table 2.1.
Example 2.1.
#!/bin/csh -f 1 if ( e file ) then echo file exists endif 2 if ( d file ) then echo file is a directory endif 3 if ( ! z file ) then echo file is not of zero length endif 4 if ( -r file && -w file ) then echo file is readable and writable endif
Table 2.1. C and TC Shell Syntax and Constructs
The shbang line |
The "shbang" line is the very first line of the script and lets the kernel know what shell will be interpreting the lines in the script. The shbang line consists of a hash mark #, an exclamation point ! (called a bang), followed by the full pathname of the shell, and any shell options. Any other lines beginning with a # are used as comments. EXAMPLE #!/bin/csh or #!/bin/tcsh |
||
Comments |
Comments are descriptive material preceded by a # sign; they are not executable statements. They are in effect until the end of a line and can be started anywhere on the line. EXAMPLE
|
||
Wildcards |
There are some characters that are evaluated by the shell in a special way. They are called shell metacharacters or "wildcards." These characters are neither numbers nor letters. For example, the *, ?, and [ ] are used for filename expansion. The ! is the history character, the < , > , >> , <&, and | symbols are used for standard I/O redirection and pipes. To prevent these characters from being interpreted by the shell they must be quoted with a backslash or quote marks. EXAMPLE
|
||
Displaying output |
To print output to the screen, the echo command is used. Wildcards must be escaped with either a backslash or matching quotes. EXAMPLE echo "Hello to you\!" |
||
Local variables |
Local variables are in scope for the current shell. When a script ends or the shell exits, they are no longer available; i.e., they go out of scope. Local variables are set and assigned values. EXAMPLE
|
||
Global variables |
Global variables are called environment variables. They are set for the currently running shell and are available to any process spawned from that shell. They go out of scope when the script ends or the shell where they are defined exits. EXAMPLE
|
||
Extracting values from variables |
To extract the value from variables, a dollar sign is used. EXAMPLE
|
||
Reading user input |
The special variable $< reads a line of input from the user and assigns it to a variable. EXAMPLE
|
||
Arguments |
Arguments can be passed to a script from the command line. Two methods can be used to receive their values from within the script: positional parameters and the argv array. EXAMPLE % scriptname arg1 arg2 arg3 ... Using positional parameters: echo $1 $2 $3arg1 is assigned to $1, arg2 to $2, etc. Using the argv array: echo $argv[1] $argv[2] $argv[3] |
||
Arrays |
An array is a list of words separated by whitespace. The list is enclosed in a set of parentheses. The built-in shift command shifts off the left-hand word in the list. Unlike C, the individual words are accessed by index values, which start at 1 rather than 0. EXAMPLE set word_list = ( word1 word2 word3 ) set names = ( Tom Dick Harry Fred ) shift names removes Tom from the list echo $word_list[1] displays first element of the list echo $word_list[2] displays second element of the list echo $word_list or $word_list[*] displays all elements of the list echo $names[1] echo $names[2] echo $names[3] echo $names or echo $names[*] |
||
Command substitution |
To assign the output of a UNIX/Linux command to a variable, or use the output of a command in a string, the command is enclosed in backquotes. Example set variable_name=`command` echo $variable_name set now = `date` The command in backquotes is executed and its output echo $now is assigned to the variable now echo "Today is `date`" The output of the date command is inserted in the string |
||
Arithmetic |
Variables that will hold the results of an arithmetic computation must be preceded by an @ symbol and a space. Only integer arithmetic is provided by this shell. EXAMPLE
|
||
Operators |
The C and TC shells support operators for testing strings and numbers similar to those found in the C language. EXAMPLE Equality: == Relational: > greater than Logical: && and |
||
Conditional statements |
The if construct is followed by an expression enclosed in parentheses. The operators are similar to C operators. The then keyword is placed after the closing parentheses. An if must end with an endif. An alternative to if/else if is the switch statement. EXAMPLE
The switch construct is: switch variable_name switch ( "$color" ) case constant1: case blue: statements echo $color is blue case constant2: breaksw
|
||
Loops |
There are two types of loops, the while and foreach loop. The while loop is followed by an expression enclosed in parentheses, a block of statements, and terminated with the end keyword. As long as the expression is true, the looping continues. The foreach loop is followed by a variable name and a list of words enclosed in parentheses, a block of statements, and terminates with the end keyword. The foreach loop iterates through a list of words, processing a word and then shifting it off, then moving to the next word. When all words have been shifted from the list, it ends. The loop control commands are break and continue. EXAMPLE
|
||
File testing |
The C shell has a built-in set of options for testing attributes of files, such as whether it is a directory, a plain file (not a directory), a readable file, and so forth. For other types of file tests, the UNIX test command is used. See Example 2.1 for a demonstration. EXAMPLE r Current user can read the file w Current user can write to the file x Current user can execute the file e File exists o Current user owns the file z File is zero length d File is a directory f File is a plain file |
2.3.1 The C/TC Shell Script
The program in Example 2.2 is an example of a C shell/TC shell script. The program contains many of the constructs discussed in Table 2.1.
Example 2.2.
1 #!/bin/csh f 2 # The Party ProgramInvitations to friends from the "guest" file 3 set guestfile = ~/shell/guests 4 if ( ! e "$guestfile" ) then echo "$guestfile:t nonexistent" exit 1 5 endif 6 setenv PLACE "Sarotini's" 7 @ Time = `date +%H` + 1 8 set food = ( cheese crackers shrimp drinks "hot dogs" sandwiches ) 9 foreach person ( `cat $guestfile` ) 10 if ( $person =~ root ) continue 11 mail v s "Party" $person << FINIS # Start of here document Hi $person! Please join me at $PLACE for a party! Meet me at $Time o'clock. I'll bring the ice cream. Would you please bring $food[1] and anything else you would like to eat? Let me know if you can make it. Hope to see you soon. Your pal, ellie@`hostname` # or `uname -n` 12 FINIS 13 shift food 14 if ( $#food == 0 ) then set food = ( cheese crackers shrimp drinks "hot dogs" sandwiches ) endif 15 end echo "Bye..."
EXPLANATION
-
This line lets the kernel know that you are running a C shell script. The f option is a fast startup. It says, "Do not execute the .cshrc file," an initialization file that is automatically executed every time a new csh program is started.
-
This is a comment. It is ignored by the shell, but important for anyone trying to understand what the script is doing.
-
The variable guestfile is set to the full pathname of a file called guests.
-
This line reads: If the file guests does not exist, then print to the screen "guests nonexistent" and exit from the script with an exit status of 1 to indicate that something went wrong in the program.
-
This marks the end of the statements based on the if condition.
-
Variables are assigned the values for the place and time. The PLACE variable is an environment variable.
-
The Time variable is a local variable. The @ symbol tells the C shell to perform its built-in arithmetic; that is, add 1 to the Time variable after extracting the hour from the date command. The Time variable is spelled with an uppercase T to prevent the C shell from confusing it with one of its reserved words, time.
-
The food array is created. It consists of a list of words separated by whitespace. Each word is an element of the food array.
-
The foreach loop consists of a list, created by using command substitution, `cat $guestfile`. The output of the cat command will create a list of guests from a file. For each person on the guest list, except the user root, a mail message will be created inviting the person to a party at a given place and time, and asking him or her to bring one of the foods on the list.
-
The condition tests to see if the value of the variable, person, matches the word root. If it does, the continue statement causes control to go immediately back to the top of the loop (rather than executing any further statements). The next word on the list will be then be processed by the foreach.
-
The mail message is created in what is called a here document. All text from the user-defined word FINIS to the final FINIS will be sent to the mail program. The foreach loop shifts through the list of names, performing all of the instructions from the foreach to the keyword end.
-
FINIS is a user-defined terminator that ends the here document, which consists of the body of an e-mail message.
-
After a message has been sent, the food list is shifted to the left with the shift command, so that the next person on the guest list will get the next food item on the list.
-
If the food list is empty, it will be reset to ensure that any additional guests will be instructed to bring a food item.
-
This marks the end of the looping statements.