Bash template
Mai jos este un template primitiv de script bash care accepta parametri. Il puteti copia, modifica sau adapta dupa nevoi cata vreme cat il folositi in scopuri nobile.
<source lang="bash">
- !/bin/bash
- bash script template version 0.1
- DBG=1
MYVERSION=0.1
- usage function
usage() { HLP="myapp version $MYVERSION usage: $0 [options] myfirstarg [mysecondarg]
options:
-param <param> sample arg with param required -h, --help this help --debug enable debug output -v, --version show version
"; echo "$HLP"; }
abort() {
ecode=$1; shift echo "Error $ecode: $@" [ $DBG ] && echo "Exit code: $ecode" exit $ecode
}
dosomestuff() {
echo "doing some stuff..."
}
dosomeotherstuff() {
echo "doing some OTHER stuff..."
}
dodefaultstuff() {
echo "doing DEFAULT stuff..."
}
- parse parameters
while [ $# -gt 0 ]; do
case "$1" in
- option requires a parameter
-param ) [ $2 ] || abort 2 "$1: requires a parameter"; MYPARAM="$2"; shift 2 ;;
-dosomestuff ) ACTION=dosomestuff; shift ;; -dosomeotherstuff ) ACTION=dosomeotherstuff; shift ;;
-q|--quiet) QUIET=1; shift;; -v|--verbose) VRB=1; shift;; -h | --help ) usage; exit 0 ;; -ver*|-version ) echo "Version $MYVERSION" ; exit 1 ;; --debug) DBG=1; shift ;; * ) if [ -z $MYFIRSTARG ]; then MYFIRSTARG="$1" elif [ -z $MYSECONDARG ]; then MYSECONDARG="$1" fi shift ;; esac
done
[ $DBG ] && VRB=1 # enable verbose output if debug enabled [ $DBG ] && echo "entering main" [ $DBG ] && echo "current internal vars: ACTION=$ACTION; MYPARAM=$MYPARAM; MYFIRSTARG=$MYFIRSTARG; MYSECONDARG=$MYSECONDARG"
[ $VRB ] && echo "print some verbose output..."
case "$ACTION" in
dosomestuff) dosomestuff;; dosomeotherstuff) dosomeotherstuff;; *) dodefaultstuff;;
esac
echo "All done." </source>
Nota: Script-ul foloseste anumite conventii specifice bash. Pentru a functiona cu /bin/sh pe alte sisteme de tip Unix este nevoie de modificari.