Difference between revisions of "Bash script template"
From Teknologisk videncenter
m |
m |
||
Line 43: | Line 43: | ||
# collect options and override default | # collect options and override default | ||
− | while getopts ' | + | while getopts ':c:t:mkrnh' CMDLINEARG |
do | do | ||
case "${CMDLINEARG}" in | case "${CMDLINEARG}" in | ||
Line 63: | Line 63: | ||
N=${OPTARG} | N=${OPTARG} | ||
;; | ;; | ||
− | h | + | h) |
usage | usage | ||
;; | ;; | ||
+ | *) echo -e "ERROR: illegal option -${OPTARG}" | ||
+ | ;; | ||
esac | esac | ||
done | done | ||
Line 87: | Line 89: | ||
Done... | Done... | ||
</source> | </source> | ||
+ | =Links= | ||
+ | *[http://wiki.bash-hackers.org/howto/getopts_tutorial getopts tutorial] | ||
[[Category:bash]][[category:Linux]] | [[Category:bash]][[category:Linux]] |
Revision as of 08:12, 2 May 2012
Below is a script template with options.
#!/bin/bash
#
# FILNAME - SHORT DESCRIPTION
#
# (c) 2012 - DONALD DUCK <dd@disney.org> - all rights reserved
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# default settings
COUNT=0
unset R # Default unset
N=1 # Default set
UNIT=""
TEXT="Distance between A and B"
usage() {
echo "usage: $0 [-mkrh] [-c count -n] [-t text]"
echo " -m m flag fx. report result in miles"
echo " -k k flag fx. report result in km"
echo " -r r flag"
echo " -c c flag with value"
echo " -n n flag - unset"
echo " -t t flag with text"
echo " -h help"
echo ""
echo " Description line1"
echo " Description line2"
exit 1
}
# collect options and override default
while getopts ':c:t:mkrnh' CMDLINEARG
do
case "${CMDLINEARG}" in
c)
COUNT=${OPTARG}
;;
t)
TEXT=${OPTARG}
;;
m|k)
[ ! -z "${UNIT}" ] && echo '-m and -k are mutually exclusive. Select miles or km.'\
&& usage
UNIT="${CMDLINEARG}"
;;
r)
R=${CMDLINEARG}
;;
n)
N=${OPTARG}
;;
h)
usage
;;
*) echo -e "ERROR: illegal option -${OPTARG}"
;;
esac
done
echo -e "Settings"
echo -e "COUNT = $COUNT"
echo -e "TEXT = $TEXT"
echo -e "UNIT = $UNIT"
echo -e "R = $R"
echo -e "N = $N"
echo -e "Done..."
Running the script - example
heth@mars:~/bin$ ./bash_template -t "Hyde" -n -m -c 67
Settings
COUNT =
TEXT = Hyde
UNIT = m
R =
N =
Done...