help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] array indirection


From: John Kearney
Subject: Re: [Help-bash] array indirection
Date: Sat, 05 May 2012 02:34:34 +0200
User-agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20120428 Thunderbird/12.0.1

Am 05.05.2012 02:20, schrieb Bill Gradwohl:
Can anyone explain why one pass of this loop works and then fails.

If it didn't work at all, or worked all the time I could understand, but working once and then quitting is confusing.

array=(11 12 13 14 15)
variableName='array'

for ((x=0; x<address@hidden; ++x)); do
   echo "array[${x}]=${!variableName[$x]}"
done
==================
Produces:
address@hidden 01.ycc# ./tst pass3
array[0]=11
./tst: line 33: !variableName[$x]: unbound variable


--
Bill Gradwohl


if you only have integers in your array you can do this
   echo "array[${x}]=$(( variableName[$x] ))"


If its not just integers its a bit more complex.
If your curious how I tend to approach this problem.
https://github.com/dethrophes/Experimental-Bash-Module-System/blob/master/bash/ArrayFuncs.sh

 
 function check_valid_var_name {
    case "${1:?Missing Variable Name}" in
      [!a-zA-Z_]* | *[!a-zA-Z_0-9]* ) return 3;;
    esac
  }
  function get_array_element {
    check_valid_var_name "${1:?Missing Variable Name}" || return $?
    check_valid_var_name "${2:?Missing Array Name}" || return $?
    #echo "${1}=\${${2}[${3:?Missing Array Index}]}"
    eval "${1}"'="${'"${2}"'["${3:?Missing Array Index}"]}"' || ErrorOut 1 "$(gettext "Error setting variable")" "${1}"
  }

   get_array_element TmpVar ${variableName} $x
   echo "array[${x}]=${TmpVar}"





--
View John
          Kearney's profile on LinkedIn John Kearney

reply via email to

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