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.
Tutorial details
Difficulty level Easy
Root privileges No
Requirements tcsh/csh
Est. reading time 5 minute

Syntax

The syntax is as follows:

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

OR
set i = 1
while ( i

OR

foreach n ( 1 2 3 4 5 )
#command1
#command2
end

Examples

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

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

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

Sample outputs:

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

csh foreach example

#!/bin/csh
echo "Setting name servers...."
foreach i ( ns1.cyberciti.biz ns2.cyberciti.biz  ) 
   echo $i 
end

Sample outputs:

Setting name servers....
ns1.cyberciti.biz
ns2.cyberciti.biz

You can use wild card with foreach as follows:

#!/bin/csh
foreach i (*)
        if (-f $i) then
            echo "$i is a file."
        endif
        if (-d $i) then
             echo "$i is a directory."
        endif
end

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
  • tcsh(1)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 2 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
2 comments… add one
  • Flávio Veras Jul 30, 2013 @ 10:01

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

  • Simrandeep Jul 17, 2016 @ 7:19

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

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum