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

Unix考古记:一个“遗
Unix Shell脚本编程知