Skip to content

Instantly share code, notes, and snippets.

@a-shevtsov
Created April 15, 2019 19:36
Show Gist options
  • Save a-shevtsov/39ebf7ba65c90f522862aae3a086db4c to your computer and use it in GitHub Desktop.
Save a-shevtsov/39ebf7ba65c90f522862aae3a086db4c to your computer and use it in GitHub Desktop.
Bash argument parsing with 'set -euo pipefail'
#!/usr/bin/env bash
# https://web.archive.org/web/20190329060125/https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
set -euo pipefail
# Set default values for mandatory arguments
CLONE_URL=''
BRANCH_NAME=''
print_help() {
cat <<HELP
Usage: $0 --clone-url <clone_url> --branch <branch_name>
Deploy app from Git repository.
--clone-url URL to clone Git repository
--branch Branch name to check out
HELP
}
# Loop through all arguments
while [[ -n "${1-}" ]]; do
case "$1" in
--clone-url)
shift
CLONE_URL="${1-}" # Use default value '' if switch is passed with no value
;;
--branch)
shift
BRANCH_NAME="${1-}"
;;
--help)
print_help
exit 0
;;
*)
echo "Unknown argument: $1"
print_help
exit 1
;;
esac
shift || true # Do not fail the script if there are no arguments left
done
if [[ -z "$CLONE_URL" ]] || [[ -z "$BRANCH" ]]; then
echo "Not all mandatory arguments were passed"
print_help
exit 2
fi
# The rest of the script goes here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment