标签:
函数用法
函数定义:
# 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/shchar_name(){_Letters_Only=$1 #_Letters_Only=`echo $1|awk ‘{if($0~/[^a-zA-X]/) print "1"}‘` #只能包含字符if [ "$_Letters_Only" != "" ]thenreturn 1elsereturn 0fi}name_error(){echo "$@ contains errors ,it ,must contain only letters"}while :doecho -n "what is your first name :"read F_Nameif char_name $F_Namethenbreakelsename_error $F_Namefidone
2、字符串转大写函数 str_to_upper
#!/bin/shstr_to_upper(){_str=$1if [ $# -ne 1 ]; thenecho "number_file: I need a string to convert please "return 1fiecho $@ | tr ‘[a-z]‘ ‘[A-Z]‘}
3、列出文本文件的行号 number_file脚本
#!/bin/shnumber_file(){_Filename=$1if [ $# -ne 1 ]; thenecho "number_file: I need a filename to number"return 1filoop=1while read Linedoecho "$loop :$Line"loop=`expr $loop + 1`done <$_Filename}
4、判断字符串是否为大写 is_upper脚本
#!/bin/shis_upper(){if [ $# -ne 1 ]; thenecho "is_upper:I need a string to test OK"return 1fi_Is_Upper=`echo $1|awk ‘{if($0~/[^A-Z]/) print "1"}‘`if [ "$_Is_Upper" != "" ]thenreturn 1elsereturn 0fi}echo -n "Enter the filename :"read FileNameif is_upper $FileName ; thenecho "Great it‘s upper case"elseecho "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/shcheck_length(){_str=$1_max=$2if [ $# -ne 2 ]; thenecho "check_length; I need a string and max length the string should be "return 1fi#check the length of the string_Length=`echo $_str|awk ‘{print length($0)}‘`if [ "$_Length" -gt "$_max" ]; thenreturn 1elsereturn 0fi}while :doecho "Enter your First name :"read Nameif check_length $Name 10thenbreakelseecho "The name field is too long 10 charater max "fidone
wc也将这些空格作为字符串的一部分。因而给出其错误的长度。awk在读取键盘时缺省截去字符串末尾处空格。
6、chop函数删除字符串前面的字符 chop脚本
#!/bin/shchop(){# to call: chop string how_many_charts_to_chop_str=$1_chop=$2chop=`expr $_chop + 1 `if [ $# -ne 2 ]; thenecho "check_length : I need a string and how manay characters to chop "return 1fi_Length=`echo $_str|awk ‘{print length($0)}‘`if [ "$_Length" -lt "$_chop" ]; thenecho "sorry you have asked to chop more characters than there ara in the string "return 1fiecho $_str |awk ‘{print substr($1,‘$_chop‘)}‘}
标签:
原文地址:http://www.cnblogs.com/liaohw/p/4782100.html