Skip to content

Instantly share code, notes, and snippets.

@s-ashwinkumar
Created September 13, 2017 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-ashwinkumar/959d5d9bb3bcf7d3596244b230620804 to your computer and use it in GitHub Desktop.
Save s-ashwinkumar/959d5d9bb3bcf7d3596244b230620804 to your computer and use it in GitHub Desktop.
Sample to show how to use getopt
#!/bin/bash
# 'arg-x' and 'x' behave like flags
# 'arg-y' and 'y' have required arguments.
# 'arg-z' and 'z' have optional arguments
# Initial value for the flag parameter (default false)
X=0
# create the option string
OPT_STR=`getopt -o xy:z:: --long arg-x,arg-y:,arg-z:: -n 'cla_script.sh' -- "$@"`
eval set -- "$OPT_STR"
# assign options to variables
while true ; do
case "$1" in
-x|--arg-x) X=1 ; shift ;; # The flag type
-y|--arg-y)
case "$2" in
"") shift 2 ;;
*) Y=$2 ; shift 2 ;;
esac ;; # The one with required arguments
-z|--arg-z)
case "$2" in
"") Z='default value' ; shift 2 ;;
*) Z=$2 ; shift 2 ;;
esac ;; # The one with optional arguments
--) shift ; break ;;
*) echo "Check Usage !" ; exit 1 ;;
esac
done
# Using the variables
echo "X is $X , Y is $Y and Z is $Z"
# $ sh cla_script.sh -x --arg-y='testing' -z
#=> X is 1 , Y is testing and Z is default value
# $ sh cla_script.sh -y 'testing' --arg-z='testing this too'
#=> X is 0 , Y is testing and Z is testing this too
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment