≡ Menu

Unix: csh Shell Loop Example

Can you give me a simple loop example in csh shell in Linux or Unix like operating systems?

The C shell (csh) or the improved version, tcsh is a Unix shell that was originally created by Bill Joy at University of California, Berkeley in the late 1970s.


The syntax is as follows:

while ( condition )
# do something
# command 1
# command 2

set i = 1
while ( i < 5 ) # do something till i < 5 # command 1 # command 2 @ i++ end


foreach n ( 1 2 3 4 5 )


The following csh code will print welcome message five times on screen:

 # demoloop.csh - Sample loop script
 set j = 1
 while ( $j <= 5 )
   echo "Welcome $j times"
   @ j++

Save and close the file. Run it as follows:
chmod +x demoloop.csh

Sample outputs:

Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

csh foreach example

echo "Setting name servers...."
foreach i ( ns1.cyberciti.biz ns2.cyberciti.biz  ) 
   echo $i 

Sample outputs:

Setting name servers....

You can use wild card with foreach as follows:

foreach i (*)
        if (-f $i) then
            echo "$i is a file."
        if (-d $i) then
             echo "$i is a directory."

Sample outputs:

mycal.pl is a file.
skl is a directory.
x is a file.
x.pl is a file.
y is a file.

Please note that csh was popular for many innovative features but csh has never been as popular for scripting. If you are writing system level rc scripts avoid using csh. You may want to use /bin/sh for any scripts that might have to run on other systems.

Recommended readings
Share this tutorial on:
{ 2 comments… add one }
  • Flávio Veras July 30, 2013, 10:01 am

    What about giving us the same examples for /bin/sh?
    Thanx in advance.

  • Simrandeep July 17, 2016, 7:19 am

    How to write script in c shell to write all numbers from input number down to 1 using loop

Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">

   Tagged with: , ,