利用 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]$
- 利用 function 功能
- 利用C++11的function和bind功能,实现QStandardItemModel的通用遍历函数
- 通用功能 | General Function
- 功能测试(Function)
- 利用Phone function 获取通话记录
- MD_STOCK_REQUIREMENTS_LIST_API这个FUNCTION的功能
- Camera Function - 摄像头功能说明
- 经典功能缺陷Function Bug
- 利用GClientGeocoder類實現找圖功能
- 利用分类实现功能
- 利用memory function 计算Fibonacci number
- 功能点 Function Point 估算法
- Function实现ALV Table五:布局功能
- Function实现ALV Table 九:编辑功能
- Function实现ALV Table五:布局功能
- 特性(Feature)与功能(Function)的差异
- 测试建模:功能列表(Function List)
- 测试建模:功能列表(Function List)
- 针对“【ASP.NET】"密码最短长度为7,其中必须包含以下非字母数字字符1"解决方法
- RPC技术
- 程序员有趣的面试智力题
- zoj 2433 Highways水题
- Zend_Session及Zend_Session_Namespace
- 利用 function 功能
- C++ Primer Chapter 1
- WinXP安装系统分区大小计算
- 用python+wxpython写的闹钟程序
- 创北机房OracleDBConsole服务无法启动解决办法
- 1816
- 计算机操作系统之三:进程与线程的描述与控制
- 未解决
- 生成随机数