Shell Script parameters [duplicate]

2019-07-18 05:44发布

This question already has an answer here:

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?

标签: bash shell
3条回答
乱世女痞
2楼-- · 2019-07-18 05:55

Use or .

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
查看更多
神经病院院长
3楼-- · 2019-07-18 06:02

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.

查看更多
爷、活的狠高调
4楼-- · 2019-07-18 06:19

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

查看更多
登录 后发表回答