0

I have an array which contains

commName[0]="ls"
commName[1]="date"
commName[2]="crontab"
commName[3]="uname"
commName[4]="hostname"

Now the array doesn't always contain these. Sometimes it can have more indices sometimes less. And the values are not always ls,date,... They can be different. Bottom line, I don't know the size nor the values of the array when I'm coding.

Every array value ls,date,... has its own unique address. So for example, ls would have /home/test/ and date would have /home/test/test2/ etc... These addresses need to be stored into a variable which will be used later on in the code. So I should have following variables according to the given array

$lsAddress
$dateAddress
$crontabAddress
$unameAddress
$hostnameAddress

Therefore, I need a way to make these variables (have in mind that I don't know ls,date,uname,....)

My approach was this

for ((j=0 ; j<${#commName[@]} ; j++))
do
  set commName[$j]Nick="hi"
  echo $(${commName[$j]}Nick)
done

What I expected this to do was to create new variables for every index of the array and set them equal to hi (just for test purposes) and then access those new variables.

Also, The new created variables Must be accessible anywhere. So, I can't have a temporary variable that keeps getting replaced.

However, this method isn't working... Is there any other way I can do this?

4

2 回答 2

1

使用eval. 尝试这个:

for ((j=0 ; j<${#commName[@]} ; j++))
do
    param=`echo ${commName[$j]}Nick`
    eval "$param=hi1"
    eval "echo \$$param"
done
于 2013-11-13T15:17:33.683 回答
1

使用两个并行数组,使命令数组中的条目与地址数组中的对应条目匹配。

commName[0]="ls"
commName[1]="date"
commName[2]="crontab"
commName[3]="uname"
commName[4]="hostname"

commAddress[0]="/home/test/"       # ls
commAddress[1]="/home/test/test2"  # date
# etc

然后,当你有一个特定的值时i,你知道${commName[i]}${commAddress[i]}一起去。

我推荐这两个数组,但您也可以考虑使用bash's 间接参数扩展。

$ commName[0]="ls"
$ lsAddress="/home/test"
$ name="${commName[0]}Address"
$ echo "${!name}"
/home/test
于 2013-11-13T15:32:46.207 回答