0

I set an array named “disks” to the following words - sdb sdc sdd

in bash shell:

declare -A disks
Machine=worker01
disks[$Machine]="sdb sdc sdd"

now we print all words as the following:

echo ${disks[@]}
sdb sdc sdd

now we want to print the first item ( that should be sdb )

echo ${disks[0]}

but no output

the same with:

echo ${disks[1]}

echo ${disks[2]}

also with:

echo ${disks[3]}

echo ${disks[4]}

what is wrong here?

also not as:

for i in {1..100}
> do
> echo ${disks[$i]}
> done

so how can I print the first words of the array “disks” - when Machine=worker01

echo ${disks[$Machine]}
4

You're assigning to disks[worker01], but trying to read from disks[0] etc. The indexes are different.

As someone commented, Bash doesn't have multidimensional arrays, and that's what you really would need here. You can simulate that roughly with with space-separated strings, but then you need to split the string explicitly.

#!/bin/bash

declare -A disks
disks["host1"]="sda sdb"
disks["host2"]="sda sdb sdc"

for m in "${!disks[@]}"; do
    # split the string to array 'd'
    IFS=' ' read -a d <<< "${disks[$m]}"
    printf "$m has disk %s\n" "${d[@]}"
done
1

Why did you declare Machines when you never use it after?

$ disks=(sdb sdc sdd)
$ echo ${disks[0]}
sdb
$ echo ${disks[1]}
sdc
$ echo ${disks[2]}
sdd
  • because each machine have the uniq disks – yael Nov 15 '18 at 11:47
  • for example how to print only the first word from - echo ${disks[$Machines]} – yael Nov 15 '18 at 11:50
  • 1
    bash doesn't support multi-dimensional arrrays at all. – Ipor Sircer Nov 15 '18 at 11:54
0

The data is in ${disks[worker01]}, not in ${disks[0]}.

I am also wondering if you are trying to use an array of arrays: An array of machines, each with an array of disks.

  • because we have 20 machines as worker01 , worker02 , etc , and each machine have the uniq disks , so my target is to build array of machines and each machines hold the disks – yael Nov 15 '18 at 12:12
  • I am confused. Linguistically that makes no sense: If you were to walk into my cheese shop with a ”I love cheese” t-shirt, and I was to ask you ”Would you like some cheese”, and you were to reply “Because I like dairy products”, then I would be confused, and no more informed about your preferences. – ctrl-alt-delor Nov 15 '18 at 12:18
0

if you are looking just to print an specific value you could use:

echo ${disks[$Machine]} | awk '{print $1}'

where $1 = index 0

OUTPUT:

sdb

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.