Boston Linux & UNIX was originally founded in 1994 as part of The Boston Computer Society. We meet on the third Wednesday of each month at the Massachusetts Institute of Technology, in Building E51.

BLU Discuss list archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

passing arrays and working with arrays in BASH



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/






BLU is a member of BostonUserGroups
BLU is a member of BostonUserGroups
We also thank MIT for the use of their facilities.

Valid HTML 4.01! Valid CSS!



Boston Linux & Unix / webmaster@blu.org