Shell脚本-Demo-29例

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

【例子:001】判断输入为数字,字符或其他

1.#!/bin/bash

2.read -p "Enter a number or string here:" input

3.case $input in

4. [0-9]) echo -e "Good job, Your input is a numberic! \n" ;;

5.[a-zA-Z]) echo -e "Good job, Your input is a character! \n" ;;

6. *) echo -e "Your input is wrong, input again! \n" ;;

7.esac

【例子:002】求平均数

1.#!/bin/bash

2.# Calculate the average of a series of numbers.

3.SCORE="0"

4.AVERAGE="0"

5.SUM="0"

6.NUM="0"

7.while true; do

8. echo -n "Enter your score [0-100%] ('q' for quit): "; read SCORE;

9. if (("$SCORE" < "0")) || (("$SCORE" > "100")); then

10. echo "Be serious. Common, try again: "

11. elif [ "$SCORE" == "q" ]; then

12. echo "Average rating: $AVERAGE%."

13. break

14. else

15. SUM=$[$SUM + $SCORE]

16. NUM=$[$NUM + 1]

17. AVERAGE=$[$SUM / $NUM]

18. fi

19.done

20.echo "Exiting."

【例子:003】自减输出

1.[scriptname: doit.sh]

2.while (( $# > 0 ))

3.do

4. echo $*

5. shift

6.done

7./> ./doit.sh a b c d e

8. a b c d e

9. b c d e

10.c d e

11.d e

12.e

【例子:004】在文件中添加前缀

1.# 人名列表

2.# cat namelist

3.Jame

4.Bob

5.Tom

6.Jerry

7.Sherry

8.Alice

9.John

10.# 脚本程序

11.# cat namelist.sh

12.#!/bin/bash

13.for name in $(cat namelist)

14.do

15. echo "name= " $name

16.done

17.echo "The name is out of namelist file"

18.# 输出结果

19.# ./namelist.sh

= Jame

= Bob

= Tom

= Jerry

= Sherry

= Alice

= John

【例子:005】批量测试文件是否存在

1.[root@host ~]# cat testfile.sh

2.#!/bin/bash

3.for file in test*.sh

4.do

5. if [ -f $file ];then

6. echo "$file existed."

7. fi

8.done

9.[root@host ~]# ./testfile.sh

10.test.sh existed.

11.test1.sh existed.

12.test2.sh existed.

13.test3.sh existed.

14.test4.sh existed.

15.test5.sh existed.

16.test78.sh existed.

17.test_dev_null.sh existed.

18.testfile.sh existed.

【例子:005】用指定大小文件填充硬盘

1.[root@host ~]# df -ih /tmp

2.Filesystem Inodes IUsed IFree IUse% Mounted on

3./dev/mapper/vg00-lvol5

4. 1000K 3.8K 997K 1% /tmp

5.[root@host ~]# cat cover_disk.sh

6.#!/bin/env bash

7.counter=0

8.max=3800

9.remainder=0

10.while true

11.do

12. ((counter=counter+1))

13. if [ ${#counter} -gt $max ];then

14. break

15. fi

16. ((remainder=counter%1000))

17. if [ $remainder -eq 0 ];then

18. echo -e "counter=$counter\tdate=" $(date)

19. fi

20. mkdir -p /tmp/temp

21. cat < testfile > "/tmp/temp/myfile.$counter"

22. if [ $? -ne 0 ];then

23. echo "Failed to write file to Disk."

24. exit 1

25. fi

26.done

27.echo "Done!"

28.[root@host ~]# ./cover_disk.sh

29.counter=1000 date= Wed Sep 10 09:20:39 HKT 2014

30.counter=2000 date= Wed Sep 10 09:20:48 HKT 2014

31.counter=3000 date= Wed Sep 10 09:20:56 HKT 2014

32.cat: write error: No space left on device

33.Failed to write file to Disk.

34.dd if=/dev/zero of=testfile bs=1M count=1

相关文档
最新文档