Skip to content

Instantly share code, notes, and snippets.

@webb
Created October 2, 2020 15:18
Show Gist options
  • Save webb/ff380b0eee96dafe1c20c2a136d85ef0 to your computer and use it in GitHub Desktop.
Save webb/ff380b0eee96dafe1c20c2a136d85ef0 to your computer and use it in GitHub Desktop.
A simple CLI parser in Bash
#!/usr/bin/env bash
print_help () { echo "Option -f \${file}: Set file"; exit 0; }
fail () { echo "Error: $*" >&2; exit 1; }
unset file
OPTIND=1
while getopts :f:h-: option
do case $option in
h ) print_help;;
f ) file=$OPTARG;;
- ) case $OPTARG in
file ) fail "Option \"$OPTARG\" missing argument";;
file=* ) file=${OPTARG#*=};;
help ) print_help;;
help=* ) fail "Option \"${OPTARG%%=*}\" has unexpected argument";;
* ) fail "Unknown long option \"${OPTARG%%=*}\"";;
esac;;
'?' ) fail "Unknown short option \"$OPTARG\"";;
: ) fail "Short option \"$OPTARG\" missing argument";;
* ) fail "Bad state in getopts (OPTARG=\"$OPTARG\")";;
esac
done
shift $((OPTIND-1))
echo "File is ${file-unset}"
for (( i=1; i<=$#; ++i ))
do printf "\$@[%d]=\"%s\"\n" $i "${@:i:1}"
done
@police999a
Copy link

@Honor1234560

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment