passing arrays and working with arrays in BASH
Tom Metro
tmetro-blu-5a1Jt6qxUNc at public.gmane.org
Fri Mar 26 18:31:12 EDT 2010
theBlueSage wrote:
> ------------ start code snippet --------------
> #!/bin/bash
> function search_array() {
> index=0
> array=( "$@" )
> #echo ${array[@]}
> let TCNT=${#array[@]}-1
> LASTVAL=${array[${#array[@]}-1]}
> while [ "$index" -lt "$TCNT" ]; do
> if [ "${array[$index]}" = "$LASTVAL" ]; then
> echo $index
> return
> fi
> let "index++"
> done
> echo ""
> }
> -------- end code snippet ----------------
>
> The result is I add the scalar to the end of the array, pass it to
> the function and then peel it off again.
It seems like you are seeking a pass-by-reference mechanism, of which
I'm not aware of a way to do that in Bash. But there are two
alternatives that you may consider a slight improvement:
1. When ever you have a function that has fixed arguments plus a
variable length list, put the fixed arguments first, so you can use
'shift' to pull them off the argument list, leaving $@ to be processed
by your loop.
2. Emulate "pass-by-reference" by converting your list argument into a
single string, then splitting it back into an array within your function.
-Tom
--
Tom Metro
Venture Logic, Newton, MA, USA
"Enterprise solutions through open source."
Professional Profile: http://tmetro.venturelogic.com/
More information about the Discuss
mailing list