Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

This chapter is from the book

This chapter is from the book

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


# This is a comment

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


rm *; ls ??; cat file[1-3]; !!
echo "How are you?"
echo Oh boy\!

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


set variable_name = value
set name = "Tom Jones"

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


setenv VARIABLE_NAME value
setenv PRINTER Shakespeare

Extracting values from variables

To extract the value from variables, a dollar sign is used.

EXAMPLE


echo $variable_name
echo $name
echo $PRINTER

Reading user input

The special variable $< reads a line of input from the user and assigns it to a variable.

EXAMPLE


echo "What is your name?"
set name = $<

 

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.
echo $* all the arguments

Using the argv array:

echo $argv[1] $argv[2]
$argv[3]
echo $argv[*] all the arguments
echo $#argv the number of arguments

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


@ n = 5 + 5
echo $n

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
>=     greater than or equal to
<       less than
<=     less than or equal to

Logical:

&&     and
||     or
!       not

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 if construct is:

if ( expression ) then 
    block of statements 
endif
              

The if/else construct is:

if ( expression ) then
   block of statements
else
   block of statements
endif

The if/else/else if construct is:

if ( expression ) then 
block of statements
else if ( expression ) then
block of statements
else if ( expression ) then
block of statements
else
block of statements
endif

   The switch construct is:        

  switch variable_name      switch ( "$color" )
   case constant1:           case blue:
   statements                echo $color is blue  
   case constant2:           breaksw
statements case green: case constant3: echo $color is green statements breaksw default: case red: statements case orange: endsw echo $color is red or orange breaksw
default: echo "Not a valid color" endsw

 

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


while ( expression )
block of statements
end

foreach variable ( word list )
block of statements
end
------------------------------
foreach color (red green blue)
echo $color
end

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 Program––Invitations to friends from the "guest" file
   3   set guestfile = ~/shell/guests
   4   if ( ! –e "$guestfile" ) then
   echo "$guestfile:t non–existent"
   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

  1. 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.

  2. This is a comment. It is ignored by the shell, but important for anyone trying to understand what the script is doing.

  3. The variable guestfile is set to the full pathname of a file called guests.

  4. 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.

  5. This marks the end of the statements based on the if condition.

  6. Variables are assigned the values for the place and time. The PLACE variable is an environment variable.

  7. 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.

  8. The food array is created. It consists of a list of words separated by whitespace. Each word is an element of the food array.

  9. 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.

  10. 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.

  11. 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.

  12. FINIS is a user-defined terminator that ends the here document, which consists of the body of an e-mail message.

  13. 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.

  14. If the food list is empty, it will be reset to ensure that any additional guests will be instructed to bring a food item.

  15. This marks the end of the looping statements.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020