你好,游客 登录 注册 搜索
背景:
阅读新闻

Unix shell自定义函数的简介及使用

[日期:2013-03-04] 来源:Linux社区  作者:陈林波 [字体:大 中 小]

二、有参函数

带参数的自定义函数,在高级语言(如,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

linux
相关资讯       Unix shell 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款