Skip to content

Commit

Permalink
fix option parsing, add missing help (#45)
Browse files Browse the repository at this point in the history
In light of the discussion in #44, option parsing needs to be more
strict. We shouldn't allow an orphaned config at the end of a line that
looks like an option to another argument. This commit ensures that the
config is either passed FIRST, or via the -c/--config option. It also
does full argument validation before calling showStatus or showHelp.
  • Loading branch information
aaronhurt authored Sep 1, 2024
1 parent 064ed4f commit 8a8358d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ is not met.
### Available Command Line Options

```text
Usage: ./zfs-replicate.sh [options] [config]
Usage: ./zfs-replicate.sh [config] [options]
POSIX shell script to automate ZFS Replication
Expand Down
23 changes: 16 additions & 7 deletions zfs-replicate.sh
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ showStatus() {

## show usage and exit
showHelp() {
printf "Usage: %s [options] [config]\n\n" "${SCRIPT}"
printf "Usage: %s [config] [options]\n\n" "${SCRIPT}"
printf "POSIX shell script to automate ZFS Replication\n\n"
printf "Options:\n"
printf " -c, --config <configFile> configuration file\n"
Expand All @@ -459,9 +459,15 @@ showHelp() {
loadConfig() {
configFile=""
status=0
help=0
## sub macros for logging
TAG="$(subTags "$TAG")"
LOG_FILE="$(subTags "$LOG_FILE")"
## check for config file as first argument for backwards compatibility
if [ $# -gt 0 ] && [ -f "$1" ]; then
configFile="$1"
shift
fi
## process command-line options
while [ $# -gt 0 ]; do
if [ "$1" = "-c" ] || [ "$1" = "--config" ]; then
Expand All @@ -470,20 +476,23 @@ loadConfig() {
shift
continue
fi
if [ "$1" = "-s" ] || [ "$1" = "--status" ]; then
status=1
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
help=1
shift
continue
fi
## unknown option - check for config file for backwards compatibility
if [ -z "$configFile" ] && [ -f "$1" ]; then
configFile="$1"
if [ "$1" = "-s" ] || [ "$1" = "--status" ]; then
status=1
shift
continue
fi
## nothing left, error out
## unknown option
writeLog "ERROR: illegal option ${1}" && exit 1
done
## someone ask for help?
if [ "$help" -eq 1 ]; then
showHelp
fi
## attempt to load configuration
if [ -f "$configFile" ]; then
# shellcheck disable=SC1090
Expand Down

0 comments on commit 8a8358d

Please sign in to comment.