In this short tutorial I will show you how to do it in bash shell.
Let's say we have a script named:script.sh
That has 3 flags (-v for verbouse, -h for help, -i for ip address as input).
The two first parameters do not really get input, but more "tell the script how to behave", while the third parameter actually gets a value from user (ip address).
The "getopts" function is a very handful function when you’re working with script where parameters and flags have to be set.
Our script will be executed as (for example):
#./script.sh -v -i 10.100.1.2
This is the content of our short script:
cat << EOF
-v verbouse mode
-i new ip address
while getopts "i:hv" flag ; do case $flag in i ) IPADDR=$OPTARG;; h ) usage;; v ) VERB=1;exit 0;; esac done
Pay attention to the options with a colon (“:”) after them need to have an argument set.
Yet if there is no column, then no argument is needed (-h, -v).
We combine while loop with "getopts" function, that will use case to determine which flags were used and what values has been assigned.