linux shell函数


函数(function)在shell script中类似自定义执行指令,可以简化程序代码。
上面的show123.sh当中,每个输入结果one, two, three其实输出的内容都一样,可以使用function来简化!
function的语法如下所示:

              function fname() {
                程序段
              }
            
fname就是自定义的执行指令名称,程序段就是我们执行的内容了。
shell script的执行是由上而下,由左而右,function的定义一定放在在程序的最前面, 这样才能够在执行时被找到。
我们将show123.sh改写一下,自定义一个名为printit的函数:
              [peter@study bin]$ vim show123-2.sh
              #!/bin/bash
              # Program:
              # Use function to repeat information.
              # History:
              # 2015/07/17 INITroot First release
              PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
              export PATH
              function printit(){
                echo -n "Your choice is "  #加上-n可以不断行继续在同一行显示echo "This program will print your selection !"
              }

              case ${1} in
                "one")
                  printit; echo ${1} | tr 'a-z' 'A-Z' # 将参数做大小写转换!
                  ;;
                "two")
                  printit; echo ${1} | tr 'a-z' 'A-Z'
                  ;;
                "three")
                  printit; echo ${1} | tr 'a-z' 'A-Z'
                  ;;
                *)
                  echo "Usage ${0} {one|two|three}"
                  ;;
              esac
            
函数名称printit, 在后续的程序段里面只要执行printit,shell script去执行function printit里面的几个程序段落!
如果某些程序代码一再地在script当中重复时,这个function可就重要的多,不但可以简化程序代码,而且可以模块化程序的设计!
建议使用vim的编辑器到/etc/init.d/目录下查阅一下文件, 自行追踪每个文件的执行情况,相信会更有心得!
function也是拥有内建变量的~他的内建变量与shell script很类似, 函数名称代表示$0,而后续接的变量也是以$1, $2...来取代
function fname() {
程序段
}
函数内的$0, $1... 等等与 shell script 的 $0 是不同的。
以上面show123-2.sh来说,假如我下达:sh show123-2.sh one 这表示在 shell script内的$1 为"one"这个字符串。
但是在printit()内的$1则与这个one无关。
我们将上面的例子再次的改写一下,让你更清楚!
              [peter@study bin]$ vim show123-3.sh
              #!/bin/bash
              # Program:
              # Use function to repeat information.
              # History:
              # 2015/07/17 INITroot First release
              PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
              export PATH

              function printit(){
                echo "Your choice is ${1}" # 这个 $1 必须要参考底下指令的下达
              }
              echo "This program will print your selection !"
              case ${1} in
                "one")
                  printit 1 #注意printit指令后面还有参数!
                  ;;
                "two")
                  printit 2
                  ;;
                "three")
                  printit 3
                  ;;
                *)
                  echo "Usage ${0} {one|two|three}"
                  ;;
              esac
            
如果输入 sh show123-3.sh one,会出现Your choice is 1, 因为程序段中写了printit 1, 那个1就会成为function中的$1。

initroot编辑整理,转载请注明www.initroot.com

100次点赞 100次阅读