Last active
March 31, 2019 00:14
-
-
Save acfatah/b45629fd9bc423174f509f2f336ed514 to your computer and use it in GitHub Desktop.
Examples how to parse bash command line arguments
This file contains hidden or 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/bash | |
# An example script how to parse a bash arguments with command | |
# link: https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash | |
# Script version | |
SCRIPT_VERSION=0 | |
# Help message | |
function usage() { | |
cat <<EOF | |
Parse bash command line arguments. | |
Usage: $(basename $0) COMMAND [OPTIONS...] [ARGUMENTS...] | |
COMMANDS: | |
example Run the example command | |
EOF | |
} | |
# Parse command | |
COMMAND=$1 | |
shift; | |
if [[ ! $COMMAND || $COMMAND = --help ]];then | |
usage | |
exit | |
fi | |
if [[ $COMMAND = --version ]]; then | |
echo "$(basename $0) version: $SCRIPT_VERSION" | |
exit | |
fi | |
# Parse options and arguments | |
SWITCH=0 | |
ARGUMENTS=() | |
while [[ $# -gt 0 ]] | |
do | |
key="$1" | |
case $key in | |
-s|--switch) | |
SWITCH=1 | |
shift # past argument | |
;; | |
-i|--input) | |
INPUT="$2" | |
shift # past argument | |
shift # past value | |
;; | |
-i=*|--input=*) | |
INPUT="${key#*=}" | |
shift # past argument=value | |
;; | |
*) # unknown option | |
ARGUMENTS+=("$1") # save it in an array for later | |
shift # past argument | |
;; | |
esac | |
done | |
set -- "${ARGUMENTS[@]}" # restore positional parameters | |
# Example command | |
if [[ $COMMAND = example ]]; then | |
echo "COMMAND is \"${COMMAND}\"" | |
echo "INPUT is \"${INPUT}\"" | |
echo "SWITCH is ${SWITCH}. Default to 0" | |
echo "Arguments is \"$@\"" | |
echo "Number of arguments: $#" | |
exit | |
fi | |
# No command specified | |
if [[ $COMMAND ]]; then | |
echo "Invalid command \"${COMMAND}\"" | |
echo | |
usage | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment