#!/bin/sh test_for() { echo "=========test for====" for i in {1..5} do echo "$i" done for file in `ls ..` do if [ -f ../${file} ];then echo "fileName:${file}" fi done } test_while() { echo "=========test while====" i=1 ####变量定义时 等号左右两边不可以由空格 while [ ${i} -le 5 ] do echo "$i" i=`expr ${i} + 1` done
dos2unix input.txt while read line do if [ "X" == "X${line}" ];then #######if语句的判断表达式一定要注意保留空格 continue; fi echo "${line}" done < input.txt } main() { test_for test_while } main $@
执行结果如下:
[xbh@bogon xbh]$ ./test.sh
=========test for====
1
2
3
4
5
fileName:dead.letter
fileName:-exec
fileName:log
fileName:mbox
fileName:pay.txt
fileName:regular_express.txt
=========test while====
1
2
3
4
5
dos2unix: converting file input.txt to UNIX format ...
a
b
c
[xbh@bogon xbh]$ cat input.txt
a
b
c
[xbh@bogon xbh]$
上面的脚本记录了shell脚本中for, while 语法的常用形式;
for 循环通常是实现对某个目录下的文件或文件夹的识别;
while循环则常用于读取配置文件中的数据,进而对这些文件进行相应的处理。
注:这里要强调的还是当在windows编辑配置文件后,一定要在文件的最末尾添加一个空行。
原文:http://www.cnblogs.com/xbh-blog/p/5022344.html