Pages

Friday, August 11, 2017

using getopt in better way

Reference Link :-

http://frodo.looijaard.name/project/getopt/misc/examples

https://linuxaria.com/howto/parse-options-in-your-bash-script-with-getopt

https://gist.github.com/cosimo/3760587

 

 

#!/bin/bash

 

# Example input and output (from the bash prompt):

# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "

# Option a

# Option c, no argument

# Option c, argument `more'

# Option b, argument ` very long '

# Remaining arguments:

# --> `par1'

# --> `another arg'

# --> `wow!*\?'

 

# Note that we use `"$@"' to let each command-line parameter expand to a

# separate word. The quotes around `$@' are essential!

# We need TEMP as the `eval set --' would nuke the return value of getopt.

TEMP=`getopt -o a:m:h:: --long action:,mode:,help:: -- "$@"`

 

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

 

# Note the quotes around `$TEMP': they are essential!

eval set -- "$TEMP"

 

while true ; do

        case "$1" in

                -h|--help) echo "Option h" ; shift ;;

                -m|--mode) echo "Option m, argument \`$2'" ; shift 2 ;;

                -a|--action) echo "Option a, argument \`$2'" ; shift 2 ;;

                --) shift ; break ;;

                *) echo "Internal error!" ; exit 1 ;;

        esac

done

 

echo "Remaining arguments:"

for arg do echo '--> '"\`$arg'" ; done