shell函数

函数由两部分组成:
[list]
[*]函数标题。
[*]函数体。
[/list]
标题是函数名。函数体是函数内的命令集合。标题名应该唯一;如果不是,将会混淆结,因为脚本在查看调用脚本前将首先搜索函数调用相应的 s h e l l。
定义函数的格式为:
函数名()
{
命令1
. . .
}
或者
function 函数名()
{ ...
}


两者方式都可行。如果愿意,可在函数名前加上关键字function,这取决于使用者。

创建函数文件
下面创建包容函数的函数文件并将之载入shell,进行测试,再做改动,之后再重新载入。
函数文件名为functions.main,内容如下
#!/bin/sh
#functions.main
#
#findit: this is front end for the basic find command
findit() {
#findit
if [ $# -lt 1 ]; then
echo "usage : findit file"
return 1;
fi
find . -name $1 -print
}
定位文件
定位文件格式为:
. /pahname/filename
现在文件已经创建好了,要将之载入shell,试键入:
$. functions.main
如果返回信息file not found,再试:
$. /functions.main
此即<点> <空格> <斜线> <文件名>,现在文件应该已载入shell。如果仍有错误,则应该仔细检查是否键入了完整路径名

检查载入函数
使用set命令确保函数已载入。set命令将在shell中显示所有的载入函数。
/home/l/g/tomotoboy/function >. function.main
/home/l/g/tomotoboy/function >set
……
_=function.main
findit ()
{
if [ $# -lt 1 ]; then
echo "usage : findit file";
return 1;
fi;
find . -name $1 -print
}
执行shell函数
要执行函数,简单地键入函数名即可。这里是带有一个参数的 findit函数,参数是某个文件
/home/l/g/tomotoboy/function >cd .
/home/l/g/tomotoboy/function >cd ..
/home/l/g/tomotoboy >findit sed.txt
./testdirec/sed.txt
./sed.txt


删除shell函数
现在对函数做一些改动。首先删除函数,使其对shell不可利用。使用unset命令完成此功能。删除函数时unset命令格式为:
unset function_name
$unset findit
如果现在键入set命令,函数将不再显示。
/home/l/g/tomotoboy >unset findit
/home/l/g/tomotoboy >set
……
_=findit
/home/l/g/tomotoboy >findit sed.txt
-bash: findit: command not found


再次定位函数
/home/l/g/tomotoboy >. function/function.main
/home/l/g/tomotoboy >findit sed.txt
./testdirec/sed.txt
./sed.txt

如果函数将从测试结果中反馈输出,那么使用替换命令可保存结果。函数调用的替换格式为:
variable_name = variable_name
函数function_name输出被设置到变量variable_name中。
char_name(){
# char_name
# to call: char_name string
# assign the argument across to new variable
_LETTER_ONLY=$1
# user awk to test for character only!
_LETTER_ONLY=`echo $1|awk '{if ($0~/[^a-z A-Z]/) print 1}'`
if [ "$_LETTER_ONLY" != "" ]
then
# oops errors
return 1
else
# constains only chars
return 0
fi
}

if char_name $F_NAME; then
echo "OK"
else
echo "ERROR"
fi
测试一下
/home/l/g/tomotoboy/function >char_name hello
/home/l/g/tomotoboy/function >echo $?
0
注意^符号的使用,当直接用在第一个括号里,意指否定或不匹配括号里内容。[^a-z A-Z] 匹配任一非字母型字符,而[^0-9]匹配任一非数字型字符。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值