当前位置:文档之家› Shell脚本-Demo-29例

Shell脚本-Demo-29例

【例子:001】判断输入为数字,字符或其他1.#!/bin/bash2.read -p "Enter a number or string here:" input3.case $input in4. [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/bash2.# Calculate the average of a series of numbers.3.SCORE="0"4.AVERAGE="0"5.SUM="0"6.NUM="0"7.while true; do8. echo -n "Enter your score [0-100%] ('q' for quit): "; read SCORE;9. if (("$SCORE" < "0")) || (("$SCORE" > "100")); then10. echo "Be serious. Common, try again: "11. elif [ "$SCORE" == "q" ]; then12. echo "Average rating: $AVERAGE%."13. break14. else15. SUM=$[$SUM + $SCORE]16. NUM=$[$NUM + 1]17. AVERAGE=$[$SUM / $NUM]18. fi19.done20.echo "Exiting."【例子:003】自减输出1.[scriptname: doit.sh]2.while (( $# > 0 ))3.do4. echo $*5. shift6.done7./> ./doit.sh a b c d e8. a b c d e9. b c d e10.c d e11.d e12.e【例子:004】在文件中添加前缀1.# 人名列表2.# cat namelist3.Jame4.Bob5.Tom6.Jerry7.Sherry8.Alice9.John10.# 脚本程序11.# cat namelist.sh12.#!/bin/bash13.for name in $(cat namelist)14.do15. echo "name= " $name16.done17.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.sh2.#!/bin/bash3.for file in test*.sh4.do5. if [ -f $file ];then6. echo "$file existed."7. fi8.done9.[root@host ~]# ./testfile.sh10.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 /tmp2.Filesystem Inodes IUsed IFree IUse% Mounted on3./dev/mapper/vg00-lvol54. 1000K 3.8K 997K 1% /tmp5.[root@host ~]# cat cover_disk.sh6.#!/bin/env bash7.counter=08.max=38009.remainder=010.while true11.do12. ((counter=counter+1))13. if [ ${#counter} -gt $max ];then14. break15. fi16. ((remainder=counter%1000))17. if [ $remainder -eq 0 ];then18. echo -e "counter=$counter\tdate=" $(date)19. fi20. mkdir -p /tmp/temp21. cat < testfile > "/tmp/temp/myfile.$counter"22. if [ $? -ne 0 ];then23. echo "Failed to write file to Disk."24. exit 125. fi26.done27.echo "Done!"28.[root@host ~]# ./cover_disk.sh29.counter=1000 date= Wed Sep 10 09:20:39 HKT 201430.counter=2000 date= Wed Sep 10 09:20:48 HKT 201431.counter=3000 date= Wed Sep 10 09:20:56 HKT 201432.cat: write error: No space left on device33.Failed to write file to Disk.34.dd if=/dev/zero of=testfile bs=1M count=1【例子:006】通过遍历的方法读取配置文件1.[root@host ~]# cat hosts.allow2.127.0.0.13.127.0.0.24.127.0.0.35.127.0.0.46.127.0.0.57.127.0.0.68.127.0.0.79.127.0.0.810.127.0.0.911.[root@host ~]# cat readlines.sh12.#!/bin/env bash13.i=014.while read LINE;do15. hosts_allow[$i]=$LINE16. ((i++))17.done < hosts.allow18.for ((i=1;i<=${#hosts_allow[@]};i++)); do19. echo ${hosts_allow[$i]}20.done21.echo "Done"22.[root@host ~]# ./readlines.sh23.127.0.0.224.127.0.0.325.127.0.0.426.127.0.0.527.127.0.0.628.127.0.0.729.127.0.0.830.127.0.0.931.Done【例子:007】简单正则表达式应用1.[root@host ~]# cat regex.sh2.#!/bin/env sh3.#Filename: regex.sh4.regex="[A-Za-z0-9]{6}"5.if [[ $1 =~ $regex ]]6.then7. num=$18. echo $num9.else10. echo "Invalid entry"11. exit 112.fi13.[root@host ~]# ./regex.sh 123abc14.123abc15.#!/bin/env bash16.#Filename: validint.sh17.validint(){18. ret=`echo $1 | awk '{start = match($1,/^-?[0-9]+$/);if (start == 0) print "1";else print "0"}'`19. return $ret20.}21.validint $122.if [ $? -ne 0 ]; then23. echo "Wrong Entry"24. exit 125.else26. echo "OK! Input number is:" $127.fi【例子:008】简单的按日期备份文件1.#!/bin/bash2.NOW=$(date +"%m-%d-%Y") # 当前日期3.FILE="backup.$NOW.tar.gz" # 备份文件4.echo "Backing up data to /tmp/backup.$NOW.tar.gz file, please wait..." #打印信息5.tar xcvf /tmp/backup.$NOW.tar.gz /home/ /etc/ /var # 同时备份多个文件到指定的tar压缩文件中6.echo "Done..."【例子:009】交互式环境select的使用1.#!/bin/bash2.echo "What is your favorite OS?"3.select OS in "Windows" "Linux/Unix" "Mac OS" "Other"4.do5. break6.done7.echo "You have selected $OS"8.root@localhost:~/training# ./select.sh9.What is your favorite OS?10.1) Windows11.2) Linux/Unix12.3) Mac OS13.4) Other14.#? 115.You have selected Windows【例子:010】批量修改文件名的脚本1.#!/bin/bash2.# we have less than 3 arguments. Print the help text:3.if [ $# -lt 3 ]; then4. cat <<-EOF5. ren -- renames a number of files using sed regular expressions6. USAGE: ren.sh 'regexp' 'replacement' files7. EXAMPLE: rename all *.HTM files in *.html:8. ren 'HTM$' 'html' *.HTM9. EOF10. exit 011.fi12.OLD="$1"13.NEW="$2"14.# The shift command removes one argument from the list of15.# command line arguments.16.shift17.shift18.# $* contains now all the files:19.for file in $*20.do21.if [ -f "$file" ]; then22. newfile=`echo "$file" | sed "s/${OLD}/${NEW}/g"`23. if [ -f "$newfile" ]; then24. echo "ERROR: $newfile exists already"25. else26. echo "renaming $file to $newfile "27. mv "$file" "$newfile"28. fi29.fi30.done31.root@localhost:~/training# ./ren.sh "HTML$" "html" file*.HTML32.renaming file10.HTML to file10.html33.renaming file1.HTML to file1.html34.renaming file2.HTML to file2.html35.renaming file3.HTML to file3.html36.renaming file4.HTML to file4.html37.renaming file5.HTML to file5.html38.renaming file6.HTML to file6.html39.renaming file7.HTML to file7.html40.renaming file8.HTML to file8.html41.renaming file9.HTML to file9.html【例子:011】break语句在脚本中的应用示例1.#!/bin/bash2.for VAR1 in 1 2 33.do4. for VAR2 in 0 55. do6. if [ $VAR1 -eq 2 -a $VAR2 -eq 0 ]7. then8. break 2 # 退出第二重循环,亦即退出整个循环9. else10. echo "第一个变量:$VAR1 第二个变量:$VAR2"11. fi12. done13.done14.root@localhost:~/training# ./test.sh15.第一个变量:1 第二个变量:016.第一个变量:1 第二个变量:5【例子:012】/dev/tty在读取人工输入中的特殊作用1.#!/bin/bash2.# 用来验证两次输入的密码是否一致3.printf "Enter your passwd: " # 提示输入4.stty -echo # 关闭自动打印输入字符的功能5.read pwd1 < /dev/tty # 读取密码6.printf "\nEnter again: " # 再次提示输入7.read pwd2 < /dev/tty # 再读取一次以确认8.stty echo # 打开自动打印输入字符的功能9.if [[ "$pwd1" == "$pwd2" ]]; then # 对两次输入的密码进行判断10. echo -e "\nPASSWORD: the same"11.else12. echo -e "\nPASSWORD: not same"13.fi14.root@localhost:~/training# ./test.sh15.Enter your passwd:16.Enter again:17.PASSWORD: the same【例子:013】/dev/null在脚本中的简单示例1.#!/bin/bash2.if grep /bin/bash $0 > /dev/null 2>&1 # 只关心命令的退出状态而不管其输出3.then # 对退出状态进行判断4. echo -e "/bin/bash in $0\n"5.else6. echo -e "/bin/bash not in $0\n"7.fi8.脚本输出:9.root@localhost:~/training# ./test.sh10./bin/bash in ./test.sh【例子:014】构建自己的bin目录存放执行脚本,然后随便执行的简单示例1.$ cd # 进入家目录2.$ mkdir bin # 创建$HOME目录下自己的bin目录3.$ mv test.sh bin # 将我们自己的脚本放到创建的bin目录下4.$ PATH=$PATH:$HOME/bin # 将个人的bin目录放到PATH中5.$ test.sh # 现在就可以直接执行自己的脚本了【例子:015】将长句子中单词长度为5及以上的单词打印出来1.#!/bin/bash2.# filename: test.sh3.sentence="When you're attracted to someone it just means that your subconscious is attracted to their subconscious, subconsciously.4.So what we think of as fate, is just two neuroses knowing they're a perfect match."5.for word in ${sentence}6.do7. new=`echo $word | tr -cd '[a-zA-Z]'` # 去除句子中的,或者'8. len=${#new} # 求长度9. if [ "$len" -ge 5 ] # 再判断10. then11. echo $new12. fi13.done14.root@localhost:~# ./test.sh15.youre16.attracted17.someone18.means19.subconscious20.attracted21.their22.subconscious23.subconsciously24.think25.neuroses26.knowing27.theyre28.perfect29.match【例子:016】根据输入的数据(年4位,月2位),来判断上个月天数1.#!/bin/bash2.get_last_day()3.{4. year=`expr substr $1 1 4`5. month=`expr substr $1 5 2`6. curr_month=`echo $month | tr -d '0'` # 去掉里面的0,方便后面计算7. echo "curr_month=$curr_month"8. last_month=`expr $curr_month - 1`9. case $last_month in10. 01|03|05|07|08|10|12|0)11. echo "上个月天数-->" 31 ;;12. 02)13. if [ `expr $year % 400` = 0 ] ; then14. echo "上个月天数-->" 2915. elif [ `expr $year % 4` = 0 ] && [ `expr $year % 100` != 0 ] ; then16. echo "上个月天数-->" 2917. else18. echo "上个月天数-->" 2819. fi ;;20. *)21. echo "上个月天数-->" 3022. esac23.}24.if [ $# -ne 1 ]; then25. echo "Usage: $0 201608"26.else27. get_last_day $128.fi29.root@localhost:~/training# ./test.sh 20160130.上个月天数--> 31【例子:017】统计文件中每个单词出现的频率1.#!/bin/sh2.# 从标准输入读取文件流,再输出出现频率的前n,默认:25个单词的列表3.# 附上出现频率的计数,按照这个计数由大到小排列4.# 输出到标准输出5.# 语法: wf [n]6.tr -cs A-Za-z\' '\n' |7. tr A-Z a-z |8. sort |9. uniq -c |10. sort -k1,1nr -k2 |11. sed ${1:-25}q12.root@localhost:~/training# wf 10 < /etc/hosts | pr -c4 -t -w8013. 6 ip 1 1 archive 1 capable14. 3 ff 1 allnodes 1 are 1 cn15. 2 localhost 1 allrouters【例子:018】使用while和break等待用户登录1.#!/bin/bash2.# 等待特定用户登录,每30秒确认一次3.# filename: wait_for_user_login.sh4.read -p "Ener username:-> " user5.while true6.do7. if who | grep "$user" > /dev/null8. then9. echo "The $user now logged in."10. break11. else12. sleep 3013. fi14.done15.root@localhost:~/shell# ./wait_for_user_login.sh16.Ener username:-> guest17.The guest now logged in.【例子:019】结合while,case,break,shift做简单的选项处理1.#!/bin/bash2.# 将标志变量设置为空值3.file= verbose= quiet= long=4.while [ $# -gt 0 ] # 执行循环直到没有参数为止5.do6. case $1 in # 检查第一个参数7. -f) file=$28. shift ;; # 移位-f,使得结尾shift得到$2的值9. -v) verbose=true10. quiet= ;;11. -q) quiet=true12. verbose= ;;13. -l) long=true ;;14. --) shift15. break ;;16. -*) echo "$0: $1: unrecongnized option >&2" ;;17. *) break ;;18. esac19.done20.~【例子:020】read读取多个变量处理,及文本遍历的两种常用方式1.#!/bin/bash2.while IFS=: read user pwd pid gid fullname homedir shell # IFS作为列之间的分隔符号,read读取多个变量3.do4. printf "The user=%s homedir=%s\n" "$user" "$homedir" # 对文本中的行进行处理5.done < /etc/passwd # 读取文件6.# 第二种方式7.#!/bin/bash8.cat /etc/passwd |9. while IFS=: read user pwd pid gid fullname homedir shell10.do11. printf "The user=%s homedir=%s\n" "$user" "$homedir"12.done【例子:021】复制目录树的两个简单脚本1.#!/bin/bash2.# 方式一3.find /root/shell -type d -print | # 寻找所有目录4. sed 's;/root/shell/;/tmp/shell/;' | # 更改名称,使用;作为定界符5. sed 's/^/mkdir -p /' | # 插入mkdir -p 命令6. sh -x # 以Shell的跟踪模式执行7.# 方式二8.find /root/shell -type d -print | # 寻找所有目录9. sed 's;/root/shell/;/tmp/shell/;' | # 更改名称,使用;作为定界符10. while read newdir # 读取新的目录名11. do12. mkdir -p $newdir13. done14.~【例子:022】发邮件给系统前10名磁盘用户,要求清理磁盘空间1.#!/bin/bash2.cd /home # 移动到目录的顶端3.du -s * | # 产生原始磁盘用量4. sort -nr | # 以数字排序,最高的在第一位5. sed 10q | # 在前10行之后就停止6. while read amount name # 将读取的数据分别作为amount, name变量7. do8. mail -s "disk usage warning" $name << EOF9.Gretings. You are one of the top 10 consumers of disk space10.on the system. Your home directory users $amount disk blocks.11.Please clean up unneeded files, as soon as possible.12.Thanks,13.Your friendly neighborhood system administrator.14.EOF15. done【例子:023】将密码文件转换为Shell邮寄列表1.#!/bin/bash2.# passwd-to-mailing-list3.#4.# 产生使用特定shell的所有用户邮寄列表5.#6.# 语法: passwd-to-mailing-list < /etc/passwd7.# 删除临时性文件8.rm -rf /tmp/*.mailing-list9.# 从标准输入中读取10.while IFS=: read user passwd uid gid name home Shell11.do12. Shell=${Shell:-/bin/sh} # 如为空shell,指/bin/sh13. file="/tmp/$(echo $Shell | sed -e 's;^/;;' -e 's;/;-;g').mailing-list"14. echo $user, >> $file15.done16.root@localhost:~# vim passwd-to-mailing-list17.root@localhost:~# passwd-to-mailing-list < /etc/passwd18.root@localhost:~# cat /tmp/bin-bash.mailing-list19.root,20.test,er,22.root@localhost:~# cat /tmp/bin-sh.mailing-list23.libuuid,24.jerry,【例子:024】变更目录时更新PS11.#!/bin/bash2.cd()3.{4. command cd "$@" # 实际改变目录5. x=$(pwd) # 取得当前目录的名称,传递给变量6. PS1="${x##*/}\$ " # 截断前面的组成部分,指定给PS17.}8.root$ # 最后输出,类似于这种,看不到目录的完整路径【例子:025】根据XML文件中的license时间来判断是否过期1.2.3.中国,福建,福州市,鼓楼区4. 1231235. hdsas_base_3.0.0.2_16Q2_RC26. _RC257971fe611f07. f04c3d1eb4bf61138. 2016-08-02 16:46:399. 30 days10.11.获得2016-08-02 16:46:39时间加上30 days12.期限,得到时间减去系统当前时间,小于7天,显示license即将在几天后过期。

相关主题