Created
March 4, 2011 16:56
-
-
Save jehiah/855086 to your computer and use it in GitHub Desktop.
a simple way to parse shell script arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# | |
# a simple way to parse shell script arguments | |
# | |
# please edit and use to your hearts content | |
# | |
ENVIRONMENT="dev" | |
DB_PATH="/data/db" | |
function usage() | |
{ | |
echo "if this was a real script you would see something useful here" | |
echo "" | |
echo "./simple_args_parsing.sh" | |
echo "\t-h --help" | |
echo "\t--environment=$ENVIRONMENT" | |
echo "\t--db-path=$DB_PATH" | |
echo "" | |
} | |
while [ "$1" != "" ]; do | |
PARAM=`echo $1 | awk -F= '{print $1}'` | |
VALUE=`echo $1 | awk -F= '{print $2}'` | |
case $PARAM in | |
-h | --help) | |
usage | |
exit | |
;; | |
--environment) | |
ENVIRONMENT=$VALUE | |
;; | |
--db-path) | |
DB_PATH=$VALUE | |
;; | |
*) | |
echo "ERROR: unknown parameter \"$PARAM\"" | |
usage | |
exit 1 | |
;; | |
esac | |
shift | |
done | |
echo "ENVIRONMENT is $ENVIRONMENT"; | |
echo "DB_PATH is $DB_PATH"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's marked as /bin/sh, but will not work in posix compliant shells (such as dash).
The "[[ ]]" for comparisons, "~=" regex matching, and "==" instead of "=" are all not supported.
If you prefer using those to the posix equivalents, the easiest thing to do would be to just change it to /bin/bash since those are bashisms.
:)