Created
April 30, 2018 13:30
-
-
Save sandfox/ac12cef627dd8aef255259129957ebbf to your computer and use it in GitHub Desktop.
opt parsing in bash
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/bash | |
for i in "$@" | |
do | |
case $i in | |
-e=*|--extension=*) | |
EXTENSION="${i#*=}" | |
shift # past argument=value | |
;; | |
-s=*|--searchpath=*) | |
SEARCHPATH="${i#*=}" | |
shift # past argument=value | |
;; | |
-l=*|--lib=*) | |
LIBPATH="${i#*=}" | |
shift # past argument=value | |
;; | |
--default) | |
DEFAULT=YES | |
shift # past argument with no value | |
;; | |
*) | |
# unknown option | |
;; | |
esac | |
done | |
echo "FILE EXTENSION = ${EXTENSION}" | |
echo "SEARCH PATH = ${SEARCHPATH}" | |
echo "LIBRARY PATH = ${LIBPATH}" | |
echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l) | |
if [[ -n $1 ]]; then | |
echo "Last line of file specified as non-opt/last argument:" | |
tail -1 $1 | |
fi |
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/bash | |
POSITIONAL=() | |
while [[ $# -gt 0 ]] | |
do | |
key="$1" | |
case $key in | |
-e|--extension) | |
EXTENSION="$2" | |
shift # past argument | |
shift # past value | |
;; | |
-s|--searchpath) | |
SEARCHPATH="$2" | |
shift # past argument | |
shift # past value | |
;; | |
-l|--lib) | |
LIBPATH="$2" | |
shift # past argument | |
shift # past value | |
;; | |
--default) | |
DEFAULT=YES | |
shift # past argument | |
;; | |
*) # unknown option | |
POSITIONAL+=("$1") # save it in an array for later | |
shift # past argument | |
;; | |
esac | |
done | |
set -- "${POSITIONAL[@]}" # restore positional parameters |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment