利用 function 功能

什么是『函数 (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]$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值