2

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?

Procurares
  • 2,169
  • 4
  • 22
  • 34

3 Answers3

4

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
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
0

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

Mandar Pande
  • 12,250
  • 16
  • 45
  • 72
0

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.

pfnuesel
  • 14,093
  • 14
  • 58
  • 71