Unix script - 7 Loop

Most languages have the concept of loops: If we want to repeat a tasktwenty times, we don't want to have to type in the code twenty times, with maybe a slight change each time.
As a result, we have for and while loops in the Bourne shell. This is somewhat fewer features than other languages, but nobody claimed that shell programminghas the power of C.

For Loops

for loops iterate through a set of values until the list is exhausted:


for.sh
#!/bin/sh
for i in 1 2 3 4 5
do
  echo "Looping ... number $i"
done

Try this code and see what it does.Note that the values can be anything at all:


for2.sh
#!/bin/sh
for i in hello 1 * 2 goodbye 
do
  echo "Looping ... i is set to $i"
done

is well worth trying. Make sure that you understand what is happeninghere. Try it without the * and grasp the idea, then re-readthe Wildcards section and try it again withthe * in place. Try it also in different directories, and with the * surrounded bydouble quotes, and try it preceded by a backslash (\*)

In case you don't have access to a shell at the moment (it is very usefulto have a shell to hand whilst reading this tutorial), the results of the above two scripts are:

Looping .... number 1
Looping .... number 2
Looping .... number 3
Looping .... number 4
Looping .... number 5

and, for the second example:

Looping ... i is set to hello
Looping ... i is set to 1
Looping ... i is set to (name of first file in current directory)
    ... etc ...
Looping ... i is set to (name of last file in current directory)
Looping ... i is set to 2
Looping ... i is set to goodbye

So, as you can see, for simply loops through whatever input it is given, until it runs out of input.

While Loops

while loops can be much more fun! (depending on your idea of fun, and howoften you get out of the house... )


while.sh
#!/bin/sh
INPUT_STRING=hello
while [ "$INPUT_STRING" != "bye" ]
do
  echo "Please type something in (bye to quit)"
  read INPUT_STRING
  echo "You typed: $INPUT_STRING"
done

What happens here, is that the echo and read statements will runindefinitely until you type "bye" when prompted.
Review Variables - Part I to see whywe set INPUT_STRING=hello before testing it. This makesit a repeat loop, not a traditional while loop.


The colon (:) always evaluates to true; whilst usingthis can be necessary sometimes, it is often preferrable to use a realexit condition. Compare quitting the above loop with the one below;see which is the more elegant. Also think of some situations in which each one would be more useful than the other:


while2.sh
#!/bin/sh
while :
do
  echo "Please type something in (^C to quit)"
  read INPUT_STRING
  echo "You typed: $INPUT_STRING"
done

Another useful trick is the while read f loop. This example uses the case statement,which we'll cover later. It reads from the file myfile, and for each line, tells you what language it thinks is being used. Each line must end with a LF (newline) - if cat myfile doesn't end with a blank line, that final line will not be processed.


while3a.sh
#!/bin/sh
while read f
do
  case $f in
        hello)          echo English    ;;
        howdy)          echo American   ;;
        gday)           echo Australian ;;
        bonjour)        echo French     ;;
        "guten tag")    echo German     ;;
        *)              echo Unknown Language: $f
                ;;
   esac
done < myfile

On many Unix systems, this can be also be done as:


while3b.sh
#!/bin/sh
while f=`line`
do
  .. process f ..
done < myfile

But since the while read f works with any *nix, and doesn't depend on theexternal program line, the former is preferable. See ExternalPrograms to see why this method uses the backtick (`).
Had I referred to $i (not $f) in the default("Unknown Language") case above - you will get no warnings or errors in this case, even though$i has not been declared or defined. For example:

$ i=THIS_IS_A_BUG
$ export i
$ ./while3.sh something
Unknown Language: THIS_IS_A_BUG
$

So make sure that you avoid typos. This is also another good reason for using ${x}and not just $x - if x="A" and you want to say "A1", you need echo ${x}1, as echo $x1 will try to use the variable x1, whichmay not exist, or may be set to B2.


I recently found an old thread on Usenet which I had been involved in, whereI actually learned more ... Google has it here..


A handy Bash (but not Bourne Shell) tip I learned recently from the Linux From Scratchproject is:

mkdir rc{0,1,2,3,4,5,6,S}.d

instead of the more cumbersome:

for runlevel in 0 1 2 3 4 5 6 S
do
  mkdir rc${runlevel}.d
done

And this can be done recursively, too:

$ cd /
$ ls -ld {,usr,usr/local}/{bin,sbin,lib}
drwxr-xr-x    2 root     root         4096 Oct 26 01:00 /bin
drwxr-xr-x    6 root     root         4096 Jan 16 17:09 /lib
drwxr-xr-x    2 root     root         4096 Oct 27 00:02 /sbin
drwxr-xr-x    2 root     root        40960 Jan 16 19:35 usr/bin
drwxr-xr-x   83 root     root        49152 Jan 16 17:23 usr/lib
drwxr-xr-x    2 root     root         4096 Jan 16 22:22 usr/local/bin
drwxr-xr-x    3 root     root         4096 Jan 16 19:17 usr/local/lib
drwxr-xr-x    2 root     root         4096 Dec 28 00:44 usr/local/sbin
drwxr-xr-x    2 root     root         8192 Dec 27 02:10 usr/sbin

We will use while loops further in the Testand Case sections.


一直很喜欢写unix shell script, 因为写那么一点点东西可以有那么多效果,投入小,产出大,爽啊. 在写IBM AIX K Shell script时,感觉不那么友好,主要是有一些格式细节要求比较严格,不太习惯,后来写惯了也就好了,下面的三个script是我为公司最近写的 一个自动备份shell script,基本要求就是每天晚上23:00自动跑起来,看file system /health used space是否超过了 60%,超过了就压缩三个目录下的 .dat, .log.文件, 压缩方式是gzip(.gz),本来 bzip2(.bz)的压缩率比 .gz要大1.5倍左右, 因为考虑到要 用 zgrep工具直接在文件中search字符串,而且影盘容量足够大,所以也就用gzip了.我自己感觉这三个 k shell script基本上把 aix 的 k shell script的一些特性都覆盖到了,所以就用这个例子, 文本分析我用了awk, 没用 perl,因为用不上perl那些超强的extended regular expression分析,我就用了awk,附件中有个awk文件的例子,awk也可以做比较复杂的分析,但肯定没有perl那样强,主要是perl超级强大的extended regular expression分析. 但是如果你要OOP而且要复杂文本分析,我建议你用perl或者如果你用java你就可以用oro来做perl文本分析,我的一个附件是在java中用oro进行文本分析的代码片段. 先讲一讲 IBM AIX k shell script的一些注意事项吧: (1) 注意 if 中括号的间距 (2) 注意数据的等于和字符串的等于 (3) 注意 function的返回只能是数值而且返回的数值不能太大 (4) 注意怎样才能给一个数组赋值-用空格分隔的一串数据赋予一个数组 其他的flow control ( if , for, case等),没有什么太需要注意的,可用本例子 直接作参考.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值