Shell Script parameters [duplicate]

2019-07-18 05:20发布

问题:

This question already has an answer here:

  • Using getopts to process long and short command line options 32 answers

What is the best way to parse parameters in shell script command, and then validate it?

For example bash someScript.sh -p <some_path> -o <some_other_param> -i (User forget to provide value).

How to parse all of this parameters and when user forget to input some parameters or value of this parameter show some error message and terminate executing of script?

回答1:

Use getopt or getopts.

There are lots of examples on this site, but here is one more:

#!/usr/bin/env bash

p_set=false
o_set=false
i_set=false
while getopts p:o:i: OPT; do
    case "${OPT}" in
        p)
            p_set=true
            some_path=${OPTARG}
            ;;
        o)
            o_set=true
            some_other_param=${OPTARG}
            ;;
        i)
            i_set=true
            # Process ${OPTARG} or report error if it's not provided
            ;;
    esac
done

if ! $i_set ; then
    echo "-i must be provided"
fi


回答2:

Search man pages of getopts. You would easily implement it.



回答3:

Of course, the man page is always a good resource. But there are also good examples on the net. When dealing with getopts, I always refer to http://mywiki.wooledge.org/BashFAQ/035. Pretty much everything you'd want to know can be found there.



标签: bash shell