shell函数功能

来源:互联网 发布:护士资格证题库软件 编辑:程序博客网 时间:2024/05/29 08:12

1. 函数


shell的函数(function),用于自定义一段程序段。用于简化代码。
语法:
funtion fname() {    //do something}

shell是自上而下,由左而右执行的。
所以函数的定义需要在调用的前面。
例如:
#!/bin/bash# author : yonggangfunction print_it(){    echo -n "Your choice is : " }case $1 in    "one")        print_it; echo $1;        ;;    "two")        print_it; echo $1;        ;;    "three")        print_it; echo $1;        ;;    *)        echo "Usage $0 (one|two|three)"        ;;esac
执行:
[work@www sh]$ sh func.sh twoYour choice is : two[work@www sh]$ sh func.sh oneYour choice is : one[work@www sh]$

2. 函数参数传递


function也拥有内置变量,与shell script类似。
$# 参数个数
$1 第一个参数
$2 第二个参数
...
$@ 所有参数
看下面例子:
#!/bin/bash# author : yonggangfunction print_param(){    echo "paramter number : " $#    echo "first paramter : " $1    echo "second paramter : " $2    echo "all paramter : " $@}print_param one two three
运行:
[work@www sh]$ sh func.sh paramter number :  3first paramter :  onesecond paramter :  twoall paramter :  one two three[work@www sh]$ 

地址:http://blog.csdn.net/yonggang7/article/details/40679111

0 0