【Linux/Unix】csh中的循环方法

1 简介

C shell(csh)以及升级版(tcsh)都是Unix shell,最初于20世纪70年代末期被加州大学伯克利分校的Bill Joy创建的。

2 语法

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

或者

set i = 1
while ( i < 5 ) 
    # do something till i < 5 
    # command 1 
    # command 2 
    @ i++   # 注意这里的 @ 
end

或者

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

3 示例

3.1 示例1

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

# 运行
chmod +x demoloop.csh
./demoloop.csh

# 结果
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

3.2 示例2

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

# 运行结果
Setting name servers....
ns1.cyberciti.biz
ns2.cyberciti.biz

3.3 示例3

#!/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

# 输出结果
mycal.pl is a file.
skl is a directory.
x is a file.
x.pl is a file.
y is a file.

4 说明

除非是使用的内容是使用csh编写的,否则推荐使用shell(sh)。说明原文如下:
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.

本人独自运营了微信公众号,用于分享个人学习及工作生活趣事,大家可以关注一波。(微信搜索“微思研”)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

⁣北潇

老板大气!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值