Getopts with optional parameters


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Getopts with optional parameters
# 1  
Old 05-21-2018
Getopts with optional parameters

Hi Unix Gurus,

i am on learning path of unix, and yet to discover many things. I came across with this requirement where i need to pass parameters but the position of parameters is not fixed so after doing some google search got to know "getopts" can handle that. So here is my code:

Code:
function show_help {
    echo "Usage: ${0} -b [bankname] -r [region] -w [windowdate]"
    echo ""
    echo "    -b: BankName"
    echo "    -r: Region"
    echo "    -w: Windowdate"
    exit 0
}
# A POSIX variable

OPTIND=1 # Reset in case getopts has been used previously in the shell.
# set -x

# Get parameters from command line
while getopts "h?b:r:w:f" opt; do
    case "$opt" in
    b)
        BankName=${OPTARG}
        ;;
    r)
        Region=${OPTARG}
        ;;
    w)
        WindowDate=${OPTARG}
	;;
    f)
	FilePattern=${OPTARG}
	;;
	h|\?)
        show_help
	    exit 0
        ;;
    esac
done

shift $((OPTIND-1))
[ "$1" = "--" ] && shift

# If required variables aren't setup, show help and exit
unset MISSING_PARAM
if [[ -z ${BankName} ]]; then
    MISSING_PARAM="${MISSING_PARAM} b"
fi
if [[ -z ${Region} ]]; then
    MISSING_PARAM="${MISSING_PARAM} r"
fi
if [[ -z ${WindowDate} ]]; then
    MISSING_PARAM="${MISSING_PARAM} w"
fi
#if [[ -z ${FilePattern} ]]; then
 #   MISSING_PARAM="${MISSING_PARAM} f"
#fi

if [[ -n ${MISSING_PARAM} ]]; then
    echo "Error: Missing required parameter(s)"
    for PARAM in ${MISSING_PARAM}; do
        echo "    -${PARAM}"
    done
    echo ""
    show_help
    exit 0
fi

well, now my requirement is i want to pass optional parameter, kindly note i am not talkin about optional arguments that i am aware of if i dont use ":" after any option it will accept optional argument for that option, but what i need is optional parameter.. so if i call my scripts like:

Code:
./myscript.sh -b ABC -r PQR -w 20180503 -f 130020003_S-VAN-Sort-CSMxx

it does not show any parameter passed to option "-f" because there is no ":" after -f... what i want is out of 4 parameters 3 are mandatory but last one should be non-mandatory so, both should work i.e
Code:
./myscript.sh -b ABC -r PQR -w 20180503 -f 130020003_S-VAN-Sort-CSMxx

and
Code:
./myscript.sh -b ABC -r PQR -w 20180503

Is there any way i can handle this in one getopts or do i need to write another case for non-mandatory parameter.

Let me know if require any other info.
TIA
# 2  
Old 05-21-2018
You can try this way
Code:
# Get parameters from command line
while getopts "b:r:w:f" opt; do
    case "$opt" in
    b)
        BankName=${OPTARG}
        ;;&
    r)
        Region=${OPTARG}
        ;;&
    w)
        WindowDate=${OPTARG}
        ;;&
    f)
        FilePattern="$2"
        ;;&
    b|r|w|f)
        shift 2
        OPTIND=1
        ;;
    *)
        show_help
        exit 0
        ;;
    esac
done

This User Gave Thanks to ctac_ For This Post:
# 3  
Old 05-21-2018
I don't think any options are mandatory (that's why they're called what they're called). Mandatory existence needs to be taken care of in the case ... esac construct.
# 4  
Old 05-22-2018
Quote:
Originally Posted by ctac_
You can try this way
Code:
# Get parameters from command line
while getopts "b:r:w:f" opt; do
    case "$opt" in
    b)
        BankName=${OPTARG}
        ;;&
    r)
        Region=${OPTARG}
        ;;&
    w)
        WindowDate=${OPTARG}
        ;;&
    f)
        FilePattern="$2"
        ;;&
    b|r|w|f)
        shift 2
        OPTIND=1
        ;;
    *)
        show_help
        exit 0
        ;;
    esac
done

thanks for the suggestion @ctac_
i tried that but it was not giving me desired result as if i give 4 parameters the last parameter i.e. "-f" was taking first parameter's argument so i made some changes and now its working for both cases: here is my final code

Code:
function show_help {
    echo "Usage: ${0} -b [bankname] -r [region] -w [windowdate]"
    echo ""
    echo "    -b: BankName"
    echo "    -r: Region"
    echo "    -w: Windowdate"
    exit 0
}
# A POSIX variable

OPTIND=1 # Reset in case getopts has been used previously in the shell.
# set -x

# Default values
TRG=".TRG"


# Get parameters from command line
while getopts "b:r:w:f" opt; do
    case "$opt" in
    b)
        BankName=${OPTARG}
echo ${OPTIND}
        ;;
    r)
        Region=${OPTARG}
echo ${OPTIND}
        ;;
    w)
        WindowDate=${OPTARG}
echo ${OPTIND}
	;;
    f)
	FilePattern=$8  #$2 was giving me RBC so ichanged to $8
echo ${OPTIND}
	;;
    b|r|w|f)
        shift 2
        OPTIND=1
        ;;
    *)
        show_help
        exit 0
        ;;
    esac
done

shift $((OPTIND-1))
[ "$1" = "--" ] && shift

# If required variables aren't setup, show help and exit
unset MISSING_PARAM
if [[ -z ${BankName} ]]; then
    MISSING_PARAM="${MISSING_PARAM} b"
fi
if [[ -z ${Region} ]]; then
    MISSING_PARAM="${MISSING_PARAM} r"
fi
if [[ -z ${WindowDate} ]]; then
    MISSING_PARAM="${MISSING_PARAM} w"
fi

#removed -f missing_param check to ignore it when no argument provided to case -f
if [[ -n ${MISSING_PARAM} ]]; then
    echo "Error: Missing required parameter(s)"
    for PARAM in ${MISSING_PARAM}; do
        echo "    -${PARAM}"
    done
    echo ""
    show_help
    exit 0
fi

so thanks for you reply i got the idea how OPTIND works..let me know if we can tweak it more?
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Question about getopts optional argument [args...]

There are many places where I can see the syntax description for optargs, which, usually boils down to this: getopts OPTSTRING VARNAME where: OPTSTRING tells getopts which options to expect and where to expect arguments VARNAME tells getopts which shell-variable to use for option reporting... (2 Replies)
Discussion started by: sharkura
2 Replies

2. Red Hat

Linux Optional Packages

Please forgive but I am new to Linux and still learning. When installing Linux (any flavor) over PXE, it asks if you want to customize which packages to install. Most engineers ask us to install all packages but this entails A LOT of clicking. Is there a way to "select all" packages by using a... (3 Replies)
Discussion started by: svolbruck
3 Replies

3. Shell Programming and Scripting

Order of getopts parameters

Hi, Does the order of argument and non-argument command line parameters matter to getopts? with a getopts line in my script of getopts p:cs opt a command line of <script> -p 5 -s only picks up the -p option, while <script> -s -p 5 picks up both. Removing the space between the p and the... (3 Replies)
Discussion started by: rojomoke
3 Replies

4. Shell Programming and Scripting

Two arguments for optional switch

How to declare the two argument for optional switch ? I have a script that search for a string in current or old zipped log file. Im using a option something like this ${basename} Since $1 can have only one argument should be passed when user select swicth -c and -o need to... (3 Replies)
Discussion started by: baraghun
3 Replies

5. Shell Programming and Scripting

getopts - optional and problem to display help

In the below code while getopts :rfw:d:s:a: options do case "$options" in r) echo reverse;; f) echo forward;; w) window=$OPTARG;; d) duration=$OPTARG;; s) search=$OPTARG;; a) value=$OPTARG;; *) help; exit;; esac done ... (2 Replies)
Discussion started by: Amutha
2 Replies

6. Shell Programming and Scripting

Optional Parameters/arguments while executing a script.

Hello, I have a shell script "Test.ksh" and I need to pass 8 parameters/arguments while executing the script ./Test.ksh 1 2 3 4 5 6 7 8 Out of these I want first 3 to be compulsory and rest 5 to be optional. Can you suggest the way to do this like and also how to pass these optional... (3 Replies)
Discussion started by: indrajit_u
3 Replies

7. Programming

Parse parameters with getopts

Hi, this is my problem I have script with two parameters -n name and -s surname. Both have arguments and I want to know how parse these parameters with getopts. When you write ./names -n John -s White it find you all persons, which name is John White, but when you write ./names -n John ... (1 Reply)
Discussion started by: frees
1 Replies

8. AIX

tuning network parameters : parameters not persist after reboot

Hello, On Aix 5.2, we changed the parameters tcp_keepinit, tcp_keepintvl and tcp_keepidle with the no command. tunrestore -R is present in inittab in the directory /etc/tunables we can clearly see the inclusion of parameters during reboot, including the file lastboot.log ... (0 Replies)
Discussion started by: dantares
0 Replies

9. Shell Programming and Scripting

How to make parameters optional?

Hi, I am trying to call a function inside a shell script. Is there a way in which I can make the parameters options in the call? Please help me with this. Thanks!!! (2 Replies)
Discussion started by: neeto
2 Replies

10. Shell Programming and Scripting

getopts takes options for parameters

Here is my post with a question about getopts. I am running korn shell on Solaris 5.8. I am trying to ensure that certain options require a parameter, which is easy enough. I have found that if multiple options are entered on the command line together, but the parameter for one of the options is... (1 Reply)
Discussion started by: UCD-Randy
1 Replies
Login or Register to Ask a Question