function
syntax
function name
{
commands
}
description
Define function name, positional parameters($1, $2,....) can be used within commands
1、 执行函数的一般语法是:
name arg1 arg2 ....argn
name是函数名,arg1 arg2 ...argn是参数
example:
#echo1 is function name
$function echo1
>{
>echo "the first parameter is $1"
>}
the below is invoking the function
$echo1 hello
example1:
$mytar () { echo "the first parameter is $1";}
$mytar apple
在一个脚本中定义的函数可能 在那个脚本和所有由这个脚本生成的子shell中使用,如:
#/bin/bash
function ls1
{
ls -l
}
cd "$1" && ls1
#!/bin/bash
#using function; invoking the function parameters
function mytar1 # same as mytar1()
{
ls -l
echo #output a white space line
echo "the parameters is $1 and $2"
}
cd "$1" && mytar1 "$2" "$3"
cd ..
#the script is terminate
invoking the script:
$source ./file3 files apple orange
above option, file3 is the script name; files is a directory; apple orange are parameters
2、FUNCTION LINK(函数嵌套)
#!/bin/bash
orange () {
echo "now is orange"
banana #call function2()
}
banana ()
{
echo "now is banana"
}
orange #invoking function orange
3、在shell中定义的函数,如想取消,用unset fuctionname 就可以了.
4.global variable(全局变量)和local variable(局部变量)
默认地,除了与函数参数关联的特别变量,其它所有的变量都是全局变量,局部变量用typeset声明
example:
banana()
{
FRUIT=banana
typeset FRUIT1=apple
printf "the are in function variables $FRUIT and $FRUIT1\n"
}
printf "the are outside fuction $FRUIT and $FRUIT1"
banana
5.recursive(递归)
#!/bin/bash
#the reverse function
reverse()
{ if [ $# -gt 0 ]; then
typeset arg="$1"
shift
reverse "$@"
echo "$arg"
fi
}
reverse $*
#the script terminate
invoking it :
$source ./file4 a b c
c
b
a
这个脚本的执行过程如下:
1.这个脚本执行reverse "$*"(它有效调用了reverse a b c )
2.函数reverse确定$#是否比0大,在这里,$#等于3(a b c)
3.因为$#比0大,所以reverse保存第一个参数$1(在这里a)在局部变量$arg中,然后调用shift从$@中删除它。现在,¥@中有两个参数b c.
4.函数reverse以缩短了的参数$@调用它自己
5.函数reverse确定$#是否比0大,在这里,$#等于2(b c)
6.因为$#比0大,所以reverse保存第一个参数$1(在这里a)在局部变量$arg中,然后调用shift从$@中删除它。现在,¥@中有一个参数c.
7.函数reverse以缩短了的参数$@调用它自己
8.函数reverse确定$#是否比0大,在这里,$#等于1(c)
9.因为$#比0大,所以reverse保存第一个参数$1(在这里a)在局部变量$arg中,然后调用shift从$@中删除它。现在,¥@中没有参数了。
10.函数reverse以缩短了的参数$@调用它自己
11.函数reverse确定$#是否比0大,因为$@中没有参数,所以函数返回
12.在调用的reverse返回以后,输出局部变量$arg, 在这里是c,然后返回。
13.在调用的reverse返回以后,输出局部变量$arg, 在这里是b,然后返回。
14.在调用的reverse返回以后,输出局部变量$arg, 在这里是a,然后返回。
6.return value(0 display success, nonzero display failure)
syntax:
return n #the n is a digit
return 是退出时返回的值。
example:
isinteractive()
{
case $- in
*i*) return 0;;当这一步成功后,后面的代码就不做了。
esac
echo "if the above success, the below steps stop"
return 1
}
ininteractive
|
阅读(2280) | 评论(0) | 转发(0) |