1

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!

1
  • I would try to avoid arrays. Difficult for porting, debugging and maintenance. Can you do something like for part in $(awk...) of awk ... | while read part; do Commented Apr 10, 2014 at 11:02

2 Answers 2

3

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")'
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.