2012/4/18 Clark J. Wang <[email protected]> > On 2012-4-18, at 19:04, ольга крыжановская <[email protected]> > wrote: > > > Clark, AFAIK you must declare the variable opt, OPTIND and OPTARG as > > function local variable. > > Sure the opt var should be local. What I posted is just pseudo code. :) > > But as I tested we should not declare OPTIND and OPTARG as local or > getopts in both global scope and functions would not work. Seems like ksh > implicitly treats them as local bars in funcs. Not sure if it's by design. > Needs confirmation from David. >
I made a simple example (the script attached):
$ ksh --version
version sh (AT&T Research) 93u 2011-02-08
$ cat OPTIND_in_func.ksh
#!/usr/bin/ksh
typeset def_local_OPT_vars=0
[[ -n $1 ]] && def_local_OPT_vars=1
function foo
{
typeset opt
if (( def_local_OPT_vars )); then
typeset OPTIND OPTARG
fi
while getopts hi: opt; do
case $opt in
h) echo "[${.sh.fun}] -$opt" ;;
i) echo "[${.sh.fun}] -$opt $OPTARG" ;;
esac
done
shift $((OPTIND - 1))
echo "[${.sh.fun}] $*"
}
typeset opt
set - -a a-main -b -c c-main main1 main2
while getopts a:bc: opt; do
case $opt in
[ac]) echo "[main] -$opt $OPTARG"
foo -h -i i-foo foo1 foo2
;;
b) echo "[main] -$opt"
foo -h -i i-foo foo1 foo2
;;
esac
done
shift $((OPTIND - 1))
echo "[main] $*"
$ ksh OPTIND_in_func.ksh
[main] -a a-main
[foo] -h
[foo] -i i-foo
[foo] foo1 foo2
[main] -b
[foo] -h
[foo] -i i-foo
[foo] foo1 foo2
[main] -c c-main
[foo] -h
[foo] -i i-foo
[foo] foo1 foo2
[main] main1 main2
$ ksh OPTIND_in_func.ksh 1
[main] -a a-main
[foo] -h
[foo] -i i-foo
OPTIND_in_func.ksh[29]: foo[19]: shift: -1: unknown option
Usage: shift [ options ] [n]
[main] -b
[foo] -h
[foo] -i i-foo
OPTIND_in_func.ksh[32]: foo[19]: shift: -1: unknown option
Usage: shift [ options ] [n]
[main] -c c-main
[foo] -h
[foo] -i i-foo
OPTIND_in_func.ksh[29]: foo[19]: shift: -1: unknown option
Usage: shift [ options ] [n]
[main] main1 main2
$
> >
> > David, can you add the comment that OPTIND and OPTARG must be function
> > local variables in such cases to getopts --man, please?
> >
> > Olga
>
OPTIND_in_func.ksh
Description: Binary data
_______________________________________________ ast-users mailing list [email protected] https://mailman.research.att.com/mailman/listinfo/ast-users
