0

Bash的命令行使用For循环

Posted in Linux at 十月 26th, 2010 / No Comments »

经常会遇到这种情况,要对一批文件挨个进行处理,又不想写一个脚本,
例如查找所有的jar包中是否存在特定的类

for f in `ls *.jar`; do jar tvf $f|grep FileAlreadyExistsException; done

注意如果使用for f in ‘*.jar’ 那么$f则是所有文件的拼接,不会产生正确的结果

再优化一下,输出jar文件名,注意用;分割语句
for f in `ls *.jar`; do echo $f; jar tvf $f|grep FileAlreadyExistsException; done

bash中的for循环有几种方式:
1.for name [ in word ] ; do list ; done
2.for (( expr1 ; expr2 ; expr3 )) ; do list ; done//注意有2层括号

其中list简单说就是一串由操作符(operator ;、&、&&、||)分隔开的管道(pipeline)序列,详情参看man bash
各给出一个简单例子:
1.
for filename in `ls`
do
cat $filename
done

2.
for((i=0; i<10; i++))
do
echo $i
done

3.每次减1
for (( i = 300; i >= 1 ;i– ))
do
#echo -ne “`date ‘+%T’` ”
echo -ne “$i ”
sleep 1
done

5. 每次减5
for (( i = 300; i >= 1 ;i– ))
do

echo -ne “$i ”

i=$(expr \( $i – 4 \));
#sleep 5

done

1 #!/bin/bash

2 # Two ways to count up to 10.

3

4 echo

5

6 # Standard syntax.

7 for a in 1 2 3 4 5 6 7 8 9 10

8 do

9   echo -n “$a ”

10 done

11

12 echo; echo

13

14 # +==========================================+

15

16 # Now, let’s do the same, using C-like syntax.

17

18 LIMIT=10

19

20 for ((a=1; a <= LIMIT ; a++)) # Double parentheses, and “LIMIT” with no “$”.

21 do

22   echo -n “$a ”

23 done                           # A construct borrowed from ‘ksh93′.

24

25 echo; echo

26

27 # +=========================================================================+

28

29 # Let’s use the C “comma operator” to increment two variables simultaneously.

30

31 for ((a=1, b=1; a <= LIMIT ; a++, b++)) # The comma chains together operations.

32 do

33   echo -n “$a-$b ”

34 done

35

36 echo; echo

37

38 exit 0

http://www.net527.cn/a/caozuoxitong/Linux/8720.html

Published in Linux

No Responses to “Bash的命令行使用For循环”

Leave a Reply

请输入算式结果(看不清请点击图片)
(必须)