zoukankan      html  css  js  c++  java
  • 《Advanced Bash-scripting Guide》学习(二):测试脚本调用的参数是否正确

    本文所选的例子来自于《Advanced Bash-scripting Gudie》一书,译者 杨春敏 黄毅

    #!/bin/bash
    
    E_WRONG_ARGS=85
    script_parameters="-a -h -m -z"    #-a=all, -h=help等等
    
    if [ $# -ne $Number_of_expected_args ]  
            then
            echo "Usage: `basename $0` $script_parameters"     #`basename $0`是这个脚本的文件名
    
            exit $E_WRONG_ARGS
    fi

    1.$Number_of_expected_args:是这个脚本的期望参数的个数

    2.$#是入参的数量(传入的位置参数变量的数量)

    3.[ $# -ne $Number_of_expected_args ],-ne 不等于,比较入参数量和期望参数的个数,这句是做一个入参的检查

    4.But,在此脚本中,并没有指定期望参数的个数,即$Number_of_expected_args,还有一个问题,这个脚本并没有检查传入参数的值是不是正确,有必要改写一下脚本,以达到预期的结果。


    目的:

    传入4个指定的参数:-a -h -m -z

    改进后的脚本:

    #!/bin/bash
    
    E_SUCCESS=0
    E_WRONG_ARGS=85
    Number_of_expected_args=4
    script_parameters="-a -h -m -z"
    
    if [ $# -eq $Number_of_expected_args ]
        then
           if [ "$1" == "-a" -a "$2" == "-h" -a "$3" == "-m" -a "$4" == "-z" ]
            then
              echo "`basename $0` parameter is ok."
              exit $E_SUCCESS
            fi
    fi
              echo "Usage: `basename $0` $script_parameters"
              exit $E_WRONG_ARGS

    脚本执行结果








  • 相关阅读:
    原码, 反码, 补码 详解
    位移运算符
    ASP.NET中httpmodules与httphandlers全解析
    MySQL count
    真正的能理解CSS中的line-height,height与line-height
    IfcEvent
    IfcWorkCalendarTypeEnum
    IfcSingleProjectInstance
    转换模型
    IfcTypeProduct
  • 原文地址:https://www.cnblogs.com/my_captain/p/7147655.html
Copyright © 2011-2022 走看看