函数定义:
# func_name 函数名
function func_name(){
#函数体内容
}
或
func_name(){
#函数体内容
}
函数调用:
func_name parm
获取函数还回值:
sum_xdr()
{
count=$1;
count=$[count*10];
echo $count;
#这里是使用echo语句,将结果输出到标准输出上,所以在主程序中可以使用变量接收}
ret=`sum_xdr 3`;
1、函数调用(只能包含字符)
#!/bin/sh
char_name()
{
_Letters_Only=$1 #
_Letters_Only=`echo $1|awk ‘{if($0~/[^a-zA-X]/) print "1"}‘` #只能包含字符
if [ "$_Letters_Only" != "" ]
then
return 1
else
return 0
fi
}
name_error()
{
echo "[email protected] contains errors ,it ,must contain only letters"
}
while :
do
echo -n "what is your first name :"
read F_Name
if char_name $F_Name
then
break
else
name_error $F_Name
fi
done
2、字符串转大写函数 str_to_upper
#!/bin/sh
str_to_upper()
{
_str=$1
if [ $# -ne 1 ]; then
echo "number_file: I need a string to convert please "
return 1
fi
echo [email protected] | tr ‘[a-z]‘ ‘[A-Z]‘
}
3、列出文本文件的行号 number_file脚本
#!/bin/sh
number_file()
{
_Filename=$1
if [ $# -ne 1 ]; then
echo "number_file: I need a filename to number"
return 1
fi
loop=1
while read Line
do
echo "$loop :$Line"
loop=`expr $loop + 1`
done <$_Filename
}
4、判断字符串是否为大写 is_upper脚本
#!/bin/sh
is_upper()
{
if [ $# -ne 1 ]; then
echo "is_upper:I need a string to test OK"
return 1
fi
_Is_Upper=`echo $1|awk ‘{if($0~/[^A-Z]/) print "1"}‘`
if [ "$_Is_Upper" != "" ]
then
return 1
else
return 0
fi
}
echo -n "Enter the filename :"
read FileName
if is_upper $FileName ; then
echo "Great it‘s upper case"
else
echo "Sorry it‘s not upper case"
fi
要测试字符串是否为小写,只需要在is_upper中替换相应的awk语句即可。此为
is_lower
_Is_Lower=`echo $1|awk ‘{if($0~/[^a-z]/) print "1"}‘`
5、 测试字符串长度 check_length脚本
#!/bin/sh
check_length()
{
_str=$1
_max=$2
if [ $# -ne 2 ]; then
echo "check_length; I need a string and max length the string should be "
return 1
fi
#check the length of the string
_Length=`echo $_str|awk ‘{print length($0)}‘`
if [ "$_Length" -gt "$_max" ]; then
return 1
else
return 0
fi
}
while :
do
echo "Enter your First name :"
read Name
if check_length $Name 10
then
break
else
echo "The name field is too long 10 charater max "
fi
done
使用wc命令接收键盘操作输入时有一个误操作。如果用户输入一个名字后,点击了几次空格键
wc也将这些空格作为字符串的一部分。因而给出其错误的长度。awk在读取键盘时缺省截去字符串末尾处空格。
6、chop函数删除字符串前面的字符 chop脚本
#!/bin/sh
chop()
{
# to call: chop string how_many_charts_to_chop
_str=$1
_chop=$2
chop=`expr $_chop + 1 `
if [ $# -ne 2 ]; then
echo "check_length : I need a string and how manay characters to chop "
return 1
fi
_Length=`echo $_str|awk ‘{print length($0)}‘`
if [ "$_Length" -lt "$_chop" ]; then
echo "sorry you have asked to chop more characters than there ara in the string "
return 1
fi
echo $_str |awk ‘{print substr($1,‘$_chop‘)}‘
}
时间: 2024-10-12 08:15:34