1. 函数
shell的函数(function),用于自定义一段程序段。用于简化代码。
语法:
funtion fname() {
//do something
}
shell是自上而下,由左而右执行的。
所以函数的定义需要在调用的前面。
例如:
#!/bin/bash
# author : yonggang
function 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 two
Your choice is : two
[work@www sh]$ sh func.sh one
Your choice is : one
[work@www sh]$
2. 函数参数传递
function也拥有内置变量,与shell script类似。
$# 参数个数
$1 第一个参数
$2 第二个参数
...
$@ 所有参数
看下面例子:
#!/bin/bash
# author : yonggang
function 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 : 3
first paramter : one
second paramter : two
all paramter : one two three
[work@www sh]$