Question

I am trying to make an array of the partitions contained in a device, here's my attempt, but it does not seem to work.

#!/bin/bash
DISK=sda
declare -a PARTS=("$(awk -v disk=$DISK '$4 ~ disk {printf "[" $2 "]=\"" $3 "\" "}' /proc/partitions)")

by themselves, the commands seem to work:

$ DISK=sda
$ awk -v disk=$DISK '$4 ~ disk {printf "[" $2 "]=\"" $3 "\" "}' /proc/partitions
[0]="7987200" [1]="7986408" 
$ declare -a PARTS=([0]="7987200" [1]="7986408" )
$ echo ${PARTS[0]}
7987200
$ echo ${PARTS[1]}
7986408

but not combined:

$ DISK=sda
$ declare -a PARTS=($(awk -v disk=$DISK '$4 ~ disk {printf "[" $2 "]=\"" $3 "\" "}' /proc/partitions))
$ echo ${PARTS[0]}
[0]="7987200"
$ echo ${PARTS[1]}
[1]="7986408"

Any help greatly appreciated!

Was it helpful?

Solution

For the evaluation to proceed with the declare command, you must pass a string with the whole content embraced by parentheses, which is the proper syntax for array declaration in bash (declare -a VAR=([key]=val ...)). For example, your command should be:

$ DISK=sda
$ declare -a PARTS='('$(awk -v disk=$DISK \
    '$4 ~ disk {printf "[" $2 "]=\"" $3 "\" "}' /proc/partitions)')'

You may as well check out what the proper syntax is by simply dumping the array. This is the result after running the awk command in my machine:

$ declare -p PARTS
declare -a PARTS='([0]="488386584" [1]="25165824" [2]="16777216" \
    [3]="8388608" [4]="438053895")'

OTHER TIPS

You don't need awk for this; the code is much cleaner in pure bash:

DISK=sda
declare -a parts   # Optional
while read maj min blks name; do
  [[ $name =~ ^$DISK ]] && parts[$min]=$blks
done < /proc/partitions
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top