Created
April 29, 2019 09:58
-
-
Save niradler/5ba6793dd60e462c70320ff458a2aee3 to your computer and use it in GitHub Desktop.
How to parse command line arguments using Bash case statements
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 | |
echo "Starting sctipt $0" | |
display_usage() { | |
echo | |
echo "Usage: $0" | |
echo | |
echo " -h, --help Display usage instructions" | |
echo " -p, --print Print welcome message" | |
echo | |
} | |
print_message() { | |
echo | |
echo "Welcome to Bash case statements!" | |
echo | |
} | |
raise_error() { | |
local error_message="$@" | |
echo "${error_message}" 1>&2; | |
} | |
argument="$1" | |
if [[ -z $argument ]] ; then | |
raise_error "Expected argument to be present" | |
display_usage | |
else | |
case $argument in | |
-h|--help) | |
display_usage | |
;; | |
-p|--print) | |
print_message | |
;; | |
*) | |
raise_error "Unknown argument: ${argument}" | |
display_usage | |
;; | |
esac | |
fi | |
echo "Finished script $0" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment