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

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

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

2、多个参数

不管是单个参数,还是多个参数,都通过检查判断,这里$#表示输入的参数个数;

$1表示输入的第一个参数,$2表示第二个,$3表示第四个,以此类推。

下面是一个截取字符串的函数:

实例3、pg chop

#!/bin/ksh
# chop
# to call:chop string how_many_chars_to_chop
chop() {
_STR=$1
_CHOP=$2

# awk's substr starts at 0,wo need to increment by one
CHOP=`expr $_CHOP + 1`

# check we have two params
if [ $# -ne 2 ]; then
  echo "check_length:I need a string and how many characters to chop"
  return 1
fi

# check the length of the string first
_LENGTH=`echo $_STR | awk '{print length($0)}'`

if [ "$_LENGTH" -lt "$_CHOP" ]; then
  echo "The length of the string is short"
  return 1
fi

echo $_STR | awk '{print substr($1,'$_CHOP')}'
}

# call the function
echo -n "Enter the string:"
read STR
echo -n "Enter the start position:"
read LEN
chop $STR $LEN

# author:_yeeXun
# date  :2013-3-2 14:17:34
# EOF

这个脚本中,定义了一个函数chop截取字符串,2个参数,分别用$1,$2表示;

$1表示被截取的字符串,$2表示截取的起始位置。执行如下:

sh chop
Enter the string:string123
Enter the start position:5
ng123

sh chop
Enter the string:_yeexunInCSDN
Enter the start position:10
CSDN

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

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