Thursday, January 26, 2006

Bashing Teil 1 - Parameter auswerten

Hi,

hier mal ein nettes script, wie mann argumenteparsen kann - wenn man die
Übergabeparameter eines scriptes bearbeiten will, dann muss man einfach $*
anstatt $# nehmen und die "local" anweisung wegnehmen.


---snip---
function test {
local VER=""
local HELP=""
local USAGE=""

local IFS_OLD=$IFS



#parse all args
while [ $# != 0 ]
do
case "x$1" in

"x--version")
VER="v";shift;;
"x--help")
HELP="h";shift;;
"x--usage")
USAGE="u";shift;;
"x--")
ENDARGS="--"
shift
break # end reading args - now are files
;;
x--*)
echo "$1: undefined option!" >&2
rm_end 1; return $?
;;

x-*)

local OPTIONS=""

for (( i=0 ; $i < ${#1} ; i=$i+1 ))
do
OPTIONS=$OPTIONS$' '${1:$i:1}
done

IFS=$' '
for i in `echo $OPTIONS`
do

case "x$i" in

"xv")
RM_VER="v";continue;;
"xh")
RM_HELP="h";continue;;
"xu")
RM_USAGE="u";continue;;

"xf")
RM_FORCE="f";continue;;
"x-")
continue;; #overread this
"xr")
RM_RECURSIVE="r";continue;;
"xR")
RM_RECURSIVE="r";continue;;
"xd")
RM_DIRECTORY="d";continue;;

x*)
#don't handle options
echo "-$i; undefined option" >&2;
rm_end 1; return $?;;
esac
done
shift;;

x*)
break
;;

esac
done

IFS=$IFS_OLD

#handle version
if [ "x$VER" == "xv" ] ; then
echo "rm function 0.1"
rm_end 0; return $?
fi
---snap---