Created
September 17, 2015 14:15
-
-
Save rickowski/8f4f43ab4cc740234a8e to your computer and use it in GitHub Desktop.
Parse arguments in a bash script. Example.
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/bash | |
#Are arguments given? | |
if [ $# -eq 0 ]; then | |
#No... Exit. | |
echo "Arguments required!" | |
exit 1 | |
fi | |
#Use getopts to parse arguments | |
# ...getopts "<Letters to check>" ... | |
# <Letters to check>: | |
# Begin with ":" to avoid error output | |
# Example: "ab:c" <- Check for Arguments -a and -c without extra parameter. | |
# and check for -b with additional parameter | |
while getopts ":ab:c" opt; do | |
case $opt in | |
a) | |
echo "Option a!" | |
;; | |
b) | |
echo "Option b! Parameter: $OPTARG" | |
;; | |
c) | |
echo "Option c!" | |
;; | |
\?) | |
#Triggered when found invalid argument | |
echo "Invalid option: -$OPTARG" | |
exit 1 | |
;; | |
:) | |
#Triggered when required parameter is missing | |
#This example: Executed script with just -b | |
echo "Option -$OPTARG requires an argument." | |
exit 1 | |
;; | |
esac | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment