Bash Shell Script - Check for a flag and grab its value

前端 未结 4 1879
遥遥无期
遥遥无期 2021-01-29 22:21

I am trying to make a shell script which is designed to be run like this:

script.sh -t application

Firstly, in my script I want to check to see

4条回答
  •  礼貌的吻别
    2021-01-29 23:07

    Use $# to grab the number of arguments, if it is unequal to 2 there are not enough arguments provided:

    if [ $# -ne 2 ]; then
       usage;
    fi
    

    Next, check if $1 equals -t, otherwise an unknown flag was used:

    if [ "$1" != "-t" ]; then
      usage;
    fi
    

    Finally store $2 in FLAG:

    FLAG=$2
    

    Note: usage() is some function showing the syntax. For example:

    function usage {
       cat << EOF
    Usage: script.sh -t 
    
    Performs some activity
    EOF
       exit 1
    }
    

提交回复
热议问题