[shell]shell脚本-求和&参数处理等

1,计算100以内数字的和
#!/bin/bash
sum=0


for i in $(seq 100);do
  sum=$[$i+$sum]
done
echo $sum


函数传递参数

#!/bin/bash
# author:菜鸟教程
# url:www.runoob.com

funWithParam(){
    echo "第一个参数为 $1 !"
    echo "第二个参数为 $2 !"
    echo "第十个参数为 $10 !"
    echo "第十个参数为 ${10} !"
    echo "第十一个参数为 ${11} !"
    echo "参数总数有 $# 个!"
    echo "作为一个字符串输出所有参数 $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73

2,计算2个数的和

$ cat sum.sh 
 #!/bin/bash  
funWithReturn()  
{  


    return $(( $1+$2 ))
}   


funWithReturn $@
ret=$?  
echo "sum = $ret"  


3.查询txl的案例
#!/bin/bash
print_help() {
    echo "Usage: $0 args1"
    exit 1
}

txl_add(){
    echo "增加通讯录"
}

txl_delete(){
    echo "删除通讯录"
}

txl_update(){
    echo "更新讯录"
}

txl_cha(){
    echo "查询通讯录"
}

main(){
    while :;do
        case $1 in
        1)
            txl_add
            ;;
        2)
            txl_delete
            ;;
        3)
            txl_update
            ;;
        4)
            txl_delete
            ;;
        *)
            print_help
            ;;
        esac
    done
}

main


4,参数处理

可以手工处理

判断变量  
read -p "input a word :" word  
if  [ ! -n "$word" ] ;then  
    echo "you have not input a word!"  
else  
    echo "the word you input is $word"  
fi  
  
判断输入参数  
#!/bin/bash  
if [ ! -n "$1" ] ;then  
    echo "you have not input a word!"  
else  
    echo "the word you input is $1"  
fi  


判断字符串是否为空:

$ [ -z $String ] #为空,则视为正确
$ echo $?
0
$ if [ ! -z $String ];do xxx ;done 
如果 String="" 或者String未定义,则都返回0

也可以借助getopts

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->#test.sh

#!/bin/bash

while getopts "a:bc" arg #选项后面的冒号表示该选项需要参数
do
        case $arg in
             a)
                echo "a's arg:$OPTARG" #参数存在$OPTARG中
                ;;
             b)
                echo "b"
                ;;
             c)
                echo "c"
                ;;
             ?)  #当有不认识的选项的时候arg为?
            echo "unkonw argument"
        exit 1
        ;;
        esac
done

现在就可以使用:
./test.sh -a arg -b -c 

./test.sh -a arg -bc
来加载了。
应该说绝大多数脚本使用该函数就可以了,如果需要支持长选项以及可选参数,那么就需要使用getopt

#! /bin/sh

while getopts a:bc arg
do
        case $arg in
        "a")
                echo "a: $OPTARG ($OPTIND)"
                ;;      
        "b")
                echo "bb ($OPTIND)"
                ;;
        "c")
                echo "ccc ($OPTIND)"
                ;;
        ?)
                echo "unkonw argument ($OPTIND)"
                ;;
        esac
done

列子1:
if [ -n "$1" ]  #如果$1即参数1不为空,又即存在参数1        # 被测试的变量被双引号引起
    then
   echo "Parameter #1 is $1"  # 使用引号来使#被转义
   fi
if [ -z "$1" ]  #如果$1即参数1为空(零),又即不存在参数1     
    then
   fi 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值