Created
March 11, 2024 19:23
-
-
Save marcogrcr/d470aff44f5e857df231beb28d2a7e2b to your computer and use it in GitHub Desktop.
POSIX compliant argument parsing example
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
#!/bin/sh | |
# Example to parse arguments in a POSIX shell file | |
# Inspired by: https://stackoverflow.com/questions/2875424/correct-way-to-check-for-a-command-line-flag-in-bash | |
# error codes | |
invalid_args=-1 | |
# arg defaults | |
value="" | |
operation="get" | |
simulate=0 | |
# arg parsing | |
usage() { | |
echo "Usage: $0 -k {key} [-v {value}] [-o {get | set | remove}] [-s]" | |
echo '-k, --key: The item key' | |
echo '-v, --value: The item value. Default is: ""' | |
echo '-o, --operation: The operation to execute. Default is: get' | |
echo '-s, --simulate: Simulate the operation execution. Default is: false' | |
exit $invalid_args | |
} | |
enumArg() { | |
v=$1 | |
shift | |
while test $# != 0 | |
do | |
if [ "$v" = "$1" ]; then | |
return | |
fi | |
shift | |
done | |
usage | |
} | |
requiredArg() { | |
if [ -z "$1" ]; then | |
usage | |
fi | |
} | |
requiredArgValue() { | |
if [ -z "$1" ]; then | |
echo "A value is required for $2" | |
exit $invalid_args | |
fi | |
} | |
while test $# != 0 | |
do | |
case "$1" in | |
-k|--key) | |
requiredArgValue "$2" '-k or --key' | |
key=$2 | |
shift ;; | |
-v|--value) | |
requiredArgValue "$2" '-v or --value' | |
value=$2 | |
shift ;; | |
-o|--operation) | |
requiredArgValue "$2" '-o or --operation' | |
enumArg "$2" 'get' 'set' 'delete' | |
operation=$2 | |
shift ;; | |
-s|--simulate) | |
parseArgSimulate | |
simulate=1 ;; | |
*) | |
usage ;; | |
esac | |
shift | |
done | |
requiredArg "$key" | |
echo " key: $key" | |
echo " value: $value" | |
echo "operation: $operation" | |
echo " simulate: $simulate" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment