Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Define a convention for parsing command-line flags #10

Merged
merged 5 commits into from
Jun 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ for URL in "${URLS[@]}"; do
done
```

### Command-line flags
### Using command-line flags

If a bash script calls another application that accepts command-line flags, use long flag names where available.

Expand All @@ -162,6 +162,55 @@ Make exceptions for flags where the short flags are extremely common and the lon

* `mkdir -p`

### Parsing command-line flags

In the same way that we prefer to use long flag names, we also prefer to implement long flag names.

```bash
print_help() {
cat <<EOF
Usage: ${0##*/} [--help] [--force] --target-file TARGET_FILE
Creates an empty file at the target path.
--help Display this help and exit.
--force Overwrite the target file, if it already exists.
--target-file TARGET_FILE The target path of the empty file.
EOF
}

TARGET_FILE=''
FORCE='false'
while [[ "$#" -gt 0 ]]; do
case "$1" in
--help)
print_help
exit
;;
--target-file)
TARGET_FILE="$2"
shift # For flag name.
shift # For flag value.
;;
--force)
FORCE='true'
shift # For flag name.
;;
*)
>&2 print_help
exit 1
esac
done
readonly TARGET_FILE
readonly FORCE

if [[ -z "${TARGET_FILE}" ]]; then
>&2 echo 'Missing parameter: TARGET_FILE'
>&2 print_help
exit 1
fi
```

There's no need to implement short flag names because our scripts are either being called by other scripts, internally, or users are copy/pasting commands from examples we've given them. Either way, we prefer to see long flag names being used.

### Error messages

* Print error messages to stderr.
Expand Down