Skip to content

Instantly share code, notes, and snippets.

@mehikmat
Last active September 20, 2018 08:09
Show Gist options
  • Save mehikmat/11212582 to your computer and use it in GitHub Desktop.
Save mehikmat/11212582 to your computer and use it in GitHub Desktop.
Parsing bash/shell command line options using getopts
#!/bin/bash
usage()
{
cat << EOF
usage: $0 options
This script can download 64 or 65 version centos.
OPTIONS:
-h Show the help and exit
-v Download type, can be '6.4' or '6.5'
-s Harddisk size
-e Verbose
EOF
}
HDD_SIZE=
VERSION=
VERBOSE=
while getopts "hv:s:e" opt
do
case $opt in
h)
usage
exit 1
;;
v)
VERSION=$OPTARG
if [ $OPTARG == 64 ] ; then
echo "64"
# your script
elif [ $OPTARG = 65 ] ; then
echo "65"
# your script
else
echo "Can't support version: $OPTARG. Must be either 64 or 65"
exit
fi
;;
s)
HDD_SIZE=$OPTARG
if [[ ! ("$OPTARG" =~ ^[0-9]+$) ]]; then
echo 'Hard disk size should be in numeric value.'
exit 1
fi
;;
e)
VERBOSE=1
;;
?)
usage
exit
;;
esac
done
if [[ -z $VERSION ]] || [[ -z $HDD_SIZE ]]
then
usage
exit 1
fi
# Rest of your script goes here
#!/bin/sh -e
# control variables
NO_ARGS=0
E_OPTERROR=85 # non-reserved code
OPT_EXIST=0
# print usage
usage(){
echo "Usage: ./parseCmdOptions -v [64|65] -s [hdd size]"
}
#check if there isn't any argument
if [ $# -eq $NO_ARGS ]; then
usage
exit $E_OPTERROR
fi
while getopts :hv:s: opt; do
OPT_EXIST=1
case $opt in
h)
usage
exit $E_OPTERROR
;;
v)
if [ $OPTARG == 64 ] ; then
echo "64"
# your script
elif [ $OPTARG = 65 ] ; then
echo "65"
# your script
else
echo "Can't support version: $OPTARG. Must be either 64 or 65"
exit
fi
;;
s)
HDD_SIZE=$OPTARG
;;
\? )
echo "Invalid option: -$OPTARG" >&2
usage
exit $E_OPTERROR;;
* ) echo "Option -$OPTARG requires an argument" >&2
usage
exit $E_OPTERROR;;
esac
done
# check if there wasn't any option
if [ $OPT_EXIST -eq $NO_ARGS ]; then
usage
exit $E_OPTERROR
fi
# rest of your script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment