1Sep/090
Using getops with Bash
Getopts is an easy tool to process and check your command line arguments in a bash script. Far easier than trying to parse out the options yourself!
Example script:
#!/bin/bash
# Example script using getops
usage () {
cat << EOF
Example Script
usage: $0 options
-h Display this message
-v Patch Version
-s Remote server to patch
EOF
}
while getopts "hv:s:" OPTION
do
case $OPTION in
h)
usage
exit 1
;;
v)
VERSION=$OPTARG
;;
s)
HOST=$OPTARG
;;
esac
done
if [[ ! -z $VERSION ]] && [[ ! -z $HOST ]]
then
echo "You selected $VERSION to be applied to $HOST!"
else
echo "You didn't tell me what to do."
usage
exit 1
fi
exit