Shell 函数

来源:互联网 发布:淘宝售后工作职责 编辑:程序博客网 时间:2024/05/16 06:57
基本的函数概念
函数定义menu()  
{
echo "\$1 is $1"
echo "this is $2"
reture 9
函数内内语句也无分号;
}函数调用menu aa bb
和C语言不同,执行函数不带括号()函数返回值menu aa bb
result=$?
echo "$result”


函数名中间不能带杠
#!/bin/bash
verify-para()
{
}
[macg@machome ~]$ sh test.sh
test.sh: line 18: `verify-para': not a valid identifier


shell函数定义必须在函数调用之前,因为shell是个顺序解释程序
#!/bin/bash

verifypara 调用

host=$1
user=$2
passwd=$3

verifypara()
{
if (( $# != 3 )); then
echo "usage: $0 $host $user $passwd" 定义
exit 1
fi
} [macg@machome ~]$ sh test.sh 192.168.1.12 macg 008421
test.sh: line 3: verifypara: command not found

注意函数退出用return,不能用exit,exit是直接退出程序
exit 不止退出函数,而是直接退出shell script,


不能用中括号条件表示式在if语句中引用函数,必须用命令/函数直接作为条件的方式在if语句中引用函数
这种方式在C语言中支持,但shell脚本中不支持
if [ getyn=1 ]
then
echo " your answer is no "
else
echo "your anser is yes "
fi[macg@mac-home ~]$ sh test.sh
input the num:
3
your answer is no 根本没执行函数getyn
也不能用赋值语句引用函数
yn=getyn
if [ yn=1 ]
then
echo " your answer is no "
else
echo "your anser is yes "
fi[macg@mac-home ~]$ sh test.sh
input the num:
3
your answer is no 根本没执行函数


简单的说,函数就只能象command一样被直接执行,不能放在条件表达式或赋值语句里


Shell的函数参数就和命令行参数一样,也是$1,$2,$n
menu()
{
echo "\$1 is $1"
echo "this is $2"
reture 9
}

menu aa bb [root@machome macg]# sh test.sh
$1 is aa
this is bb当调用一个函数时,shell主程序的参数,$*,$@,$#,$1,$2等等将会被函数中的参数所替换.即函数中,$1,$2,$3是函数参数,$#是参数个数


总之,函数和command几乎一模一样
只能直接执行,不能用在赋值语句或if表达式里
函数参数和命令行参数格式相同
也有返回值,返回值变量也是$?