现在的位置: 首页 > 综合 > 正文

Shell Scripts 基础例程

2018年04月17日 ⁄ 综合 ⁄ 共 7273字 ⁄ 字号 评论关闭
(1)数学运算
  
例程1:
   #/bin/bash
   echo "input your first number"
   read num1
   echo "input your second number"
   read num2
   total1=$(($num1*$num2))   #求积
   total2=$(($num1%$num2))   #求余
   echo "total=$total"
   注意:数学运算的这种写法: var=$(())    #两个括号,或declare -i var,这样声明了var是一整型数.
 
(2)判断条件test用法
   例程2:
   1.用户首先输入一文件名,判断该文件是否存在.若不存在,则中断程序.
   2.若文件存在,判断它是目录还是文件.
   3.判断执行者对该文件或目录所拥有的权限.
   #!/bin/bash
   echo "Please input filename"
   read filename
   test -e $filename && echo "$filename exit" || echo "$filename not exit" || exit 0
   test -d $filename && echo "$filename is directory"
   test -f $filename && echo "$filename is a regular file"
   test -r $filename && echo "$filename r"
   test -w $filename && echo "$filename w"
   test -x $filename && echo "$filenmae x"
      执行结果:
   Please input filename
   /home/lishuai exit
   /home/lishuai is directory
   /home/lishuai r
   /home/lishuai w
   /home/lishuai x
  
(3)判断符号[]用法
   例程3:
   1.当执行一程序时,会让用户选择Y或N.
   2.若用户输入Y或y时,提示"ok,continue".
   3.若用户输入N或n时,提示"Oh,interrupt!".
   4.若用户不是输入Y/y、N/n,提示"i do not know your choice!".
    #!/bin/bash
    echo "Please input your choice:"
    read choice
    [ "&choice == "Y" -o "$choice == "y" ] && echo "Ok,continue" && exit 0
    [ "&choice == "N" -o "$choice == "n" ] && echo "Oh,interrupt" && exit 0
    echo "I do not know your choice" && exit 0
   例程4:
     #!/bin/sh
     folder=/home
     [ -r "$folder" ] && echo "Can read $folder"    #/home目录文件可读,故执行echo后的语句
     [ -f "$folder" ] || echo "this is not file"    #/home是目录文件,不是普通文件,故执行echo后的语句
     [ -e "$folder" ] && echo "$folder exit"        #/home目录存在,故执行echo后的语句
     [ -s "$folder" ] || echo "$folder is 0"        #/home目录大小不为0,故不执行echo后的语句
     执行结果:
     can read /home
     this is not file
     /home exit
     从该例程可以看出,判断条件(test)与判断符号([])的用法十分类似.
 
(4)条件判断if...then...的用法
   例程5(该例程是例程3的拓展):if...then...
      #!/bin/bash
      echo "Please input your choice"
      read choice
      if [ "$choice" == "Y" ] || [ "$choice" == "y" ];then
           echo "ok,continue"
           exit 0
      fi
      if [ "$choice" == "N" ] || [ "$choice" == "n" ];then
           echo "Oh,interrupt"
           exit 0
      fi
      echo "I do not know your choice,Please input again" && exit 0
   Attention!!!
   <1>中括号中各个组件之间必须以空格作为分隔符.
   <2>中括号外各个组件之间必须以空格作为分隔符.如中括号与if之间有一空格,中括号与"||"之间有一空格.
   <3>";"与方括号"]"之间有没有空格都无所谓,表示这一条语句的结束.推荐加上空格.
   <4>"then"与";"之间有没有空格都无所谓.推荐加上空格.
   <5>在中括号内各组件均用双引号引起来.
   例程6(该例程是例程3的拓展):if...elif...else
      #!/bin/bash
      echo "Please input your choice"
      read choice
      if [ "$choice" == "Y" ] || [ "$choice" == "y" ];then
           echo "ok,continue"
           exit 0
      elif [ "$choice" == "N" ] || [ "$choice" == "n" ];then
           echo "Oh,interrupt"
           exit 0
      else
           echo "I do not know your choice,Please input again" && exit 0
      fi
   例程7:
   1.在程序后接第一个参数是否为"hello",如果是,则执行相应动作.
   2.如果没有加任何参数,则执行相应动作.
   3.如果加入的参数不是hello,则执行相应的动作.
     #!/bin/bash
     echo "please excute your result with parameter"
     if [ "$1" = "hello" ];then
          echo "hello embeded"
     elif [ -z "$1" ];then
          echo "you must input parameter"
     elif [ "$1" != "hello" ];then
          echo "you must input the first parameter:hello"
     else
          echo "you are wrong!"
     fi
 
(5)条件判断case...esac的用法
   case...esac语句常用在字符串匹配.比如Linux的服务启动放置目录在/etc/init.d内,其中有一syslog服务,若要重启该服务,必须执行:
  /etc/init.d/syslog restart
   重点是restart.脚本/etc/init.d/syslog可以执行不同的动作,具体什么动作,由该脚本的第一个参数来决定,此时就可以使用case...esac来判断.
   例程8(该例程是例程7的拓展):
      #!/bin/bash
      case $1 in
      "hello")
           echo "hello embeded"
           ;;
      "")
           echo "you must input parameter with hello"
           ;;
      *)
           echo "use $0 {hello}"
           ;;
      esac
   从该例程可以类推如何使/etc/init.d/syslog执行不同的动作.这点经常遇到.比如重启nfs服务器,则输入命令service nfs restart;查看Samba服务器的状态,则输入命令service smb status,(自己理解)这些命令的输出信息就可以通过case...esac语句而实现.比如当可执行命令的第一个参数是restart,则表示重启该服务器;当可执行命令的第一个参数是status,则表示要查询服务器的状态,可用echo将服务器状态输出.
  
Attenton!!!
   case...esac条件判断语句是通过不同的变量值来执行不同的动作.注意,该变量值可由两种途径获取.一种是执行某可执行程序时直接由参数获取,另一种是通过read从终端键盘获取.
   例程9
   #!/bin/bash
   echo "Hit a key,then hit return."
   read Keypress
   case "Keypress" in
      [A-Z])
            echo "Uppercase letter";;
      [a-z])
            echo "Lowercase letter";;
      [0-9])
            echo "Digit";;
      *)
            echo "Punctuation,whitespace,or other";;
   esac  
  
(6)Shell函数的用法
   例程10:该例程可用Shell函数来实现,也可用case...esac来实现.
  #!/bin/bash
  #在脚本的开头定义一函数
  function hehe(){
      echo -n "your choice is"    # -n表示下一个输出不在新一行,仍在当前行
  }
  echo "Please input your choice:"
  case $1 in
    "one")
        hehe;echo $1
        ;;
    "two")
        hehe;echo $1
        ;;
    "three")
        hehe;echo $1
        ;;
    *)
        echo "you are wrong"
        ;;
    esac
    执行结果:
    (1)若执行#sh test9.sh one ,则输出:your choice is one
    (2)若执行#sh test9.sh two ,则输出:your choice is two
    (3)若执行#sh test9.sh three ,则输出:your choice is three
    (4)若执行#sh test9.sh four ,则输出:your choice is you are wrong
    (自己的理解)可以这样来理解,由于执行结果中都有"your choice is",为了简化程序代码,可以将这条语句封装成函数.实际执行时,比如执行hehe;echo $1 时,可以理解为 echo -n "your choice is" echo $1
   例程11:练习函数的参数
     Shell脚本中的函数也有自己的变量,其中,$0表示函数名,$1表示该函数的第一个参数,$2表示该函数的第二个参数,以此类推.注意,这里的$0、$1、$2...与脚本的$0、$1、$2...所表示的含义不同.前者是函数的参数,后者是脚本内函数的参数.
   test10.sh
   #!/bin/bash
   function haha(){
   echo "your choice is $1" #由于(第一次出现的)$1在函数体内部,因此$1表示函数haha()的第一个参数
   }
   echo "Please input your choice:"
   case $1 in     #由于(第二次出现的)$1在函数体外部,因此$1表示脚本文件test10.sh的第一个参数
   "one")
      haha 1     #1直接加在函数haha()的后面,表示该函数的第一个参数就是1,即第一次出现的$1的值为1
      ;;
   "two")
      haha 2     #2直接加在函数haha()的后面,表示该函数的第一个参数就是2,即第一次出现的$1的值为2
      ;;
   "three")
      haha 3     #3直接加在函数haha()的后面,表示该函数的第一个参数就是3,即第一次出现的$1的值为3
      ;;
    *)
      echo "you are wrong"
      ;;
   esac
   执行结果:
      [root@localhost lishuai]# sh test10.sh one
      输出结果: your choice is 1
      [root@localhost lishuai]# sh test10.sh two
      输出结果: your choice is 2
      [root@localhost lishuai]# sh test10.sh three
      输出结果: your choice is 3
 
(7)循环(while...do...done、until...do...done)的用法
   例程12:假如要让用户输入yes或YES才结束程序,否则一直提示用户.
   #!/bin/bash
   echo "Please input your choice:"
   read input
   while [ "$input" != "yes"] && [ "$input" != "YES" ]
   do
       echo -p "please input yes/YES to stop your program" input
   done
  
   #!/bin/bash
   echo "Please input your choice:"
   read input
   until [ "$input" == "yes" ] || [ "$input" == "YES" ]
   do
      echo -p "please input yes/YES to stop your program" input
   done
   例程13:计算1+2+3+...+100
     方法1:
     #!/bin/bash
     i=0
     sum=0
     while [ "$i" != "100" ]
     do
          i=$(($i+1))
          sum=$(($sum+$i))
     done
     echo "the result is $sum"
       
     方法2:
     #!/bin/bash
     declare -i i=0
     declare -i sum=0
     while [ "$i" != "100" ]    #使用declare -i声明后,表示变量i和sum都是整数,要取其值,仍要加上$
     do
          i=$i+1
          sum=$sum+$i
     done
     echo "the result is $sum"
  
(8)循环(for...do...done)的用法
   例程14:  计算1+2+3+...+100
   #!/bin/bash
   sum=0
   for (( i=0; i<=100; i=i+1 ))   #也可以写成 for (( i=0; i<=100; i++ ))
   do
       sum=$(($sum+$i))
   done
   echo "the result is $sum"
   例程15:
   #!/bin/sh
   for day in Sun Mon Tue Wed Thu Fri Sat
   do
       echo $day
   done
   执行结果:
    Sun
    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
   例程16:如果列表被包含在一对双引号中,则被认为是一个元素
     #!/bin/sh
     for day in "Sun Mon Tue Wed Thu Fri Sat" 
     do
         echo $day
     done
    执行结果:
    Sun Mon Tue Wed Thu Fri Sat
  
(9)综合例程
   例程17: 
   1.用户输入任意目录,找出该目录内文件名的权限.
   2.列出只具有可执行权限的文件
   #!/bin/bash
   echo "Please input directory"
   read dir
   if [ "$dir" == "" ] || [ ! -d "$dir" ]     #判断该目录是否为空,或并非目录文件
   then
        echo "$dir not exit! Please input again!"
        exit 0
   fi
   filelist=`ls $dir`     #将 ls $dir 的返回值赋给变量filelist,这里必须使用优先执行符,否则视为字符串
   echo "the content of $dir is $filelist"
   for filename in $filelist     #变量filename可取的值都在变量$filelist中
   do
        test -r "$dir/$filename" && echo "$filename readable"
        test -w "$dir/$filename" && echo "$filename writeable"
        test -x "$dir/$filename" && echo "$filename executable"
   done
   for filename in $filelist
   do
        [ -x "$dir/$filename" ] && echo "$filename excutable"   #只列出具有可执行权限的文件
   done
【上篇】
【下篇】

抱歉!评论已关闭.