bug-bash
[Top][All Lists]
Advanced

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

Indirect access to variables, including arrays (was Re: Compare 2 arrays


From: Linda Walsh
Subject: Indirect access to variables, including arrays (was Re: Compare 2 arrays.)
Date: Wed, 06 Jun 2012 20:07:53 -0700
User-agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.24) Gecko/20100228 Lightning/0.9 Thunderbird/2.0.0.24 Mnenhy/0.7.6.666



Greg Wooledge wrote:
The only Bourne-family shell that can manipulate arrays whose names are
passed to a function is ksh93, with its "nameref" command.  Bash has
nothing analogous to that yet.
=============

I don't understand.

Are you saying that ${!nameofvar} isnt' supported?


I need a function to test to see if a word was already in
an array (no I haven't made it space/bracket...whatever proof...just a bit
more work)
But it uses indirect access to an array passed in and seem to
work fine.

So I am unclear as to what you are referring to?
I used named vars instead of $1/$2...but it's likely a similar
approach, and it's done w/o a loop (put the array in to an
assoc array, and then test to see if the element exists in the
assoc array)...

#!/bin/bash

# ex: _in "expr" <name of array>
#                       _in file.c @
#                       returns shell true/false (0/1)

function _in {
  local exp=${1:?};
        local arr=${2:?};
        read d t rest < <(typeset -p "$arr")
        if [[ ${t//[^a]/} != a ]]; then
                echo "var ${!arr} is not an array"
                return 1
        fi
        local -A _Assoc_
local str=$( printf "declare -A _Assoc_=(";printf '[%s]=1 ' $(eval "echo \${$arr[@]}") ; printf ")")
        eval "$str"
        ((${_Assoc_[$exp]}))
}


declare -a foo1=(one two three buckle the tree)
for w in how does the tree get buckled on one; do
        _in $w foo1 && echo $w
done
----
_in.shh
the
tree
one



reply via email to

[Prev in Thread] Current Thread [Next in Thread]