二、有参函数
带参数的自定义函数,在高级语言(如,C,JAVA,C#等)中,参数都是在函数后面的括号中;
而shell中则在函数体内检查参数个数。在调用函数的时候,直接在后面跟着参数即可。
无论参数有多少个,都紧跟在函数名后面。
1、单个参数
实例2、脚本如下:
pg direc_check
#!/bin/ksh
is_directory() {
_DIR_NAME=$1
# check params
if [ $# -lt 1 ]; then
echo "is_directory:I need a directory name to check"
return 1
fi
# check
if [ ! -d $_DIR_NAME ]; then
return 1
else
return 0
fi
}
error_msg() {
echo "**********"
echo $@
echo "**********"
return 0
}
echo -n "Enter destination directory:"
read DIR
if is_directory $DIR
then
echo "$DIR is a directory and exists in $PWD"
else
error_msg "$DIR does not exist ... creating it now"
mkdir $DIR > /dev/null 2>&1
if [ $? -ne 0 ]; then
error_msg "Could not create directory::chech it out!"
exit 1
else :
fi
fi
# author:_yeeXun
# date :2013-3-2 15:27:57
# EOF
这里函数中# check params部分就是在做参数检查,这里$#表示输入的参数个数。
下面是执行这个脚本:
sh direc_check
Enter destination directory:test
**********
test does not exist ... creating it now
**********
再次执行时候,输入同样的名称,则会提示此目录已经存在。
sh direc_check
Enter destination directory:test
test is a directory and exists in /usr/b4nx/user/ytcclb
我们在添加一个目录,通过awk语言查看当前目录下通过此脚本创建的目录:
ls -l | awk '{if($0~/^d/) print $0}'
drwxr-xr-x 2 b4nx group 512 Mar 2 15:32 call_fun_test
drwxr-xr-x 2 b4nx group 512 Mar 2 15:04 test
