Last active
November 29, 2018 22:10
-
-
Save ouyi/5714e70c1a243b110cdffb596a754417 to your computer and use it in GitHub Desktop.
Bash boilerplate code for parsing command-line args
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
#/usr/bin/env bash | |
#set -euo pipefail | |
EXIT_SUCCESS=0 | |
EXIT_FAILURE=1 | |
IFS='' read -r -d '' USAGE <<HEREDOC | |
Copy-reinvented to showcase Bash heredoc usage and command-line arguments handling. | |
Use <<-HEREDOC to suppress leading tabs (but not spaces) in the output. | |
Use <<\HEREDOC or <<'HEREDOC' to disable parameter substitution within the heredoc body. | |
Test with a trailing backlash: \\ | |
Test with more special characters: $EXIT_FAILURE < $EXIT_SUCCESS | |
Usage: $(basename "$0") [OPTIONS] <SOURCE> <DESTINATION> | |
Options: | |
-f, --force-overwrite When set to true (defaults to false), the file exists at DESTINATION will be overwritten | |
-d, --dry-run When set to true (defaults to false), the command to be executed will be printed to stdout | |
-h, --help Print this info | |
Example: | |
$(basename "$0") --force-overwrite="true" --dry-run "source.txt" "destination.txt" | |
HEREDOC | |
# Parse options | |
for i in "$@"; do | |
case $i in | |
-f=*|--force-overwrite=*) | |
# Get the value on the righ-hand side of the equal sign | |
FORCE_OVERWRITE="${i#*=}" | |
shift | |
;; | |
-d|--dry-run) | |
# Option of the flag style | |
DRY_RUN="true" | |
shift | |
;; | |
-h|--help) | |
echo "$USAGE" | |
exit "$EXIT_SUCCESS" | |
;; | |
-*) | |
echo "Error: unknown option $i. Use '-h' for help." | |
exit "$EXIT_FAILURE" | |
;; | |
esac | |
done | |
# Set defaults using noop (:) | |
: ${FORCE_OVERWRITE="false"} | |
: ${DRY_RUN="false"} | |
# Get the positional parameters and do some validation at the same time | |
SOURCE=${1:?"Error: missing SOURCE. Use '-h' for help."} | |
DESTINATION=${2:?"Error: missing DESTINATION. Use '-h' for help."} | |
# Do the work | |
command="cp" | |
# Trim the parameter | |
if [[ "${FORCE_OVERWRITE// }" == "true" ]]; then | |
command="$command -f" | |
fi | |
command="$command $SOURCE $DESTINATION" | |
if [[ "${DRY_RUN// }" == "true" ]]; then | |
echo "$command" | |
else | |
${command} | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment