利用 function 功能

来源:互联网 发布:centos6dns网络配置 编辑:程序博客网 时间:2024/06/07 05:21

 什么是『函数 (function)』功能啊?简单的说,其实, 函数可以在 shell script 当中做出一个类似自订运行命令的东西,最大的功能是,

 可以简化我们很多的程序码~

function 的语法是这样的:

functionfname(){

          程序段

}

那个 fname 就是我们的自订的运行命令名称~而程序段就是我们要他运行的内容了。要注意的是,因为 shell script 的运行方式是由上而下,由左而右因此在 shell script 当中的 function 的配置一定要在程序的最前面, 这样才能够在运行时被找到可用的程序段喔!我们将之前的脚本改写成自订一个名为 printit 的函数来使用喔:

#!/bin/bash
#Use function to repeat information

function printit(){
   echo -n "Your choice is :"           #加上-n可以不断行继续在同一行显示
}

echo "This program will print your selcetion!"
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

我们来测试一下:

[oracle@99bill-as9 zy]$ sh function.sh oh
This program will print your selcetion!
Usage:function.sh {one|two|three}
[oracle@99bill-as9 zy]$ sh function.sh one
This program will print your selcetion!
Your choice is :ONE
[oracle@99bill-as9 zy]$ sh function.sh two
This program will print your selcetion!
Your choice is :TWO
[oracle@99bill-as9 zy]$ sh function.sh three
This program will print your selcetion!
Your choice is :THREE

另外, function 也是拥有内建变量的~他的内建变量与 shell script 很类似, 函数名称代表示 $0 ,而后续接的变量也是以 $1, $2... 来取代的~ 这里很容易搞错喔~因为『function fname() { 程序段 } 』内的 $0, $1... 等等与 shell script 的 $0 是不同的。以上面脚本来说,假如我下达:『 sh function.sh one 』 这表示在 shell script 内的 $1 为 "one" 这个字串。但是在 printit() 内的 $1 则与这个 one 无关。 我们将上面的例子再次的改写一下,让你更清楚!

#!/bin/bash
#Use function to repeat information.

function printit(){
   echo "Your choice is $1"
}

case $1 in
  "one")
    printit 1
   ;;
  "two")
    printit 2
   ;;
   "three")
    printit 3
   ;;
   *)
   echo "Usage:$0 {one|two|three}"
   ;;
esac

测试结果:

[oracle@99bill-as9 zy]$ sh function2.sh
Usage:function2.sh {one|two|three}
[oracle@99bill-as9 zy]$ sh function2.sh one
Your choice is 1
[oracle@99bill-as9 zy]$ sh function2.sh two
Your choice is 2
[oracle@99bill-as9 zy]$ sh function2.sh three
Your choice is 3
[oracle@99bill-as9 zy]$

原创粉丝点击