Created
November 7, 2012 13:23
-
-
Save skarllot/4031562 to your computer and use it in GitHub Desktop.
Handling parameters into bash scripts
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 | |
# | |
# Copyright (C) 2007 kace | |
# http://bsdpants.blogspot.de/2007/02/option-ize-your-shell-scripts.html | |
readonly USAGE='usage: '`basename $0`' [-13ds] [-o out-file] filename' | |
snmpver=2c | |
sync=0 | |
debug=0 | |
while [[ ${1:0:1} = '-' ]] ; do | |
N=1 | |
L=${#1} | |
while [[ $N -lt $L ]] ; do | |
case ${1:$N:1} in | |
'd') debug=1 ;; | |
's') sync=1 ;; | |
'1') snmpver=1 ;; | |
'3') snmpver=3 ;; | |
'o') if [[ $N -ne $(($L-1)) || ! -n ${2} ]] ; then | |
echo $USAGE | |
exit 1 | |
fi | |
outfile=${2} | |
shift ;; | |
*) echo $USAGE | |
exit 1 ;; | |
esac | |
N=$(($N+1)) | |
done | |
shift | |
done | |
if [[ ! -n ${1} ]] ; then | |
echo $USAGE | |
exit 1 | |
fi | |
infile=$1 | |
echo -n "snmpver:$snmpver debug:$debug sync:$sync " | |
echo "outfile:$outfile infile:$infile" |
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
$ optionize.bsh | |
usage: optionize.bsh [-13ds] [-o ] filename | |
$ #that last argument _is_ required | |
$ | |
$ optionize.bsh blah | |
snmpver:2c debug:0 sync:0 outfile: infile:blah | |
$ #defaults | |
$ | |
$ optionize.bsh -s1 -o yada blah | |
snmpver:1 debug:0 sync:1 outfile:yada infile:blah | |
$ #blobs are fine | |
$ | |
$ optionize.bsh -sd1 -o yada -3 blah | |
snmpver:3 debug:1 sync:1 outfile:yada infile:blah | |
$ #last option on the command line overrides any previous | |
$ | |
$ optionize.bsh -s -d -d1o yada -3o Yadaya blah | |
snmpver:3 debug:1 sync:1 outfile:Yadaya infile:blah | |
$ #options requiring arg.s can be in a blob, but ... | |
$ | |
$ optionize.bsh -d -so1 yada blah | |
usage: optionize.bsh [-13ds] [-o ] filename | |
$ # ... not in the middle of a blob, obviously. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment