passing arrays and working with arrays in BASH

theBlueSage tbs-Gb/NUjX2UK8 at public.gmane.org
Fri Mar 26 17:12:33 EDT 2010


Ho Folks,

so it has taken me _ages_ to get this to work and Icant believe this is
the best/only way to get this done :

Problem : 
I am writing server install scripts, and BASH is the chosen tool. I
needed to write a function that could receive an array and a value, and
then simply return the position in the array if the given value. This is
seriously easy in something like PHP using in_array($arr, $val), but in
was a completely different kettle of fish in BASH.

Solution (that I have working right now, in example form):

------------ 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 ""
}


echo -e -n "enter a value to search for : "
read -e KEY
arr=( f q e c d s a )
arr[${#arr[@]}+1]=$KEY
position=$(search_array "${arr[@]}")
if [ -z "$position" ]; then
    echo -e "the value "$KEY" is not in the array"
else
    echo -e "the value "$KEY" was found at position: "$position
fi
exit 0


-------- end code snippet ----------------

where : 'KEY' is the value to search for and 'arr' is the array to
search in


I did it this way as I couldn't find any other way to pass an array
_and_ a scalar value to the function. The result is I add the scalar to
the end of the array, pass it to the function and then peel it off
again.

SURELY there is a better way of doing it than this ?

thanks for any suggestions


Richard

-- 
theBlueSage <tbs-Gb/NUjX2UK8 at public.gmane.org>







More information about the Discuss mailing list