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

前端 未结 4 1881
遥遥无期
遥遥无期 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:04

    You should read this getopts tutorial.

    Example with -a switch that requires an argument :

    #!/bin/bash
    
    while getopts ":a:" opt; do
      case $opt in
        a)
          echo "-a was triggered, Parameter: $OPTARG" >&2
          ;;
        \?)
          echo "Invalid option: -$OPTARG" >&2
          exit 1
          ;;
        :)
          echo "Option -$OPTARG requires an argument." >&2
          exit 1
          ;;
      esac
    done
    

    Like greybot said(getopt != getopts) :

    The external command getopt(1) is never safe to use, unless you know it is GNU getopt, you call it in a GNU-specific way, and you ensure that GETOPT_COMPATIBLE is not in the environment. Use getopts (shell builtin) instead, or simply loop over the positional parameters.

提交回复
热议问题