Skip to content

Instantly share code, notes, and snippets.

@niradler
Created April 29, 2019 09:58
Show Gist options
  • Save niradler/5ba6793dd60e462c70320ff458a2aee3 to your computer and use it in GitHub Desktop.
Save niradler/5ba6793dd60e462c70320ff458a2aee3 to your computer and use it in GitHub Desktop.
How to parse command line arguments using Bash case statements
#!/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