三、函数返回值
函数的返回值表示执行函数的一个状态,
1、return 0:正常返回。
2、return 1:返回错误。
3、return :最后的命令执行状态决定返回值,可使用$?检测。
四、函数调用
1、同脚本
脚本中,函数必须在脚本一开始就定义,定义之后才可调用。
同一脚本中,在顶部定义函数,定义完后再调用,如实例1、实例2、实例3。
2、脚本间
可以将这些函数定义在同一个脚本中,作为公共使用的函数脚本,然后再需要调用的脚本中引用此脚本即可。
引用方式如下:<dot><space><directory><script>
实例4、函数调用 — 跨脚本
函数脚本:
pg direc_check.sh
#!/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
调用此脚本中函数的脚本:
pg fun_test
#!/bin/ksh
# call the function outside the script is_drectory
# <dot><space><directory with functions><script with functions>
. $HOME/user/ytcclb/direc_check.sh
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 now"
mkdir $DIR > /dev/null 2>&1
if [ $? -ne 0 ]; then
error_msg "Could not create directory::check it out"
exit 1
else :
fi
fi
# author:_yeeXun
# date :2013-3-2 15:49:12
# EOF
当输入一个已存在的目录时候:
sh fun_test
Enter destination directory:test
test is a directory and exists in /usr/b4nx/user/ytcclb
输入不存在的目录名:
sh fun_test
Enter destination directory:dir_test
**********
dir_test does not exist ... creating now
**********
查看当前目录下所有目录名:
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 4 14:16 dir_test
drwxr-xr-x 2 b4nx group 512 Mar 2 15:04 test
--the end--
