10

Im trying to put the contents of a simple command in to a bash array however im having a bit of trouble.

df -h | awk '{ print  $5" "$6 }'

gives percentage used in the file systems on my system output looks like this:

1% /dev
1% /dev/shm
1% /var/run
0% /var/lock
22% /boot
22% /home
22% /home/steve

I would then like to put each of these lines into a bash array array=$(df -h| awk '{ print $5 $6 }')

However when I print out the array I get the following:

5%
/
1%
/dev
1%
/dev/shm
1%
/var/run
0%
/var/lock
22%
/boot
22%
/home
22%
/home/steve

Bash is forming the array based on white spaces and not line breaks how can i fix this?

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
  • What do you want to do with the array after having it in bash ? I mean ... probably you can do that in awk ... – Dr. belisarius Oct 29 '10 at 22:17
  • Well the next part of the script would be to run something similar to this command "find . -type f -exec du -sh {} \; | sort -h" on the chosen file system (user would choose a file system that is filling up too much from the array in part one). I would like to modify this second command to just show the 10 biggest files in the file system so the user can choose if to delete them or not –  Oct 29 '10 at 22:26

3 Answers3

10

You need to reset the IFS variable (the delimeter used for arrays).

OIFS=$IFS #save original
IFS=','
df -h | awk '{ print $5" "$6"," }'
Brian Clements
  • 3,787
  • 1
  • 25
  • 26
1

You could do this in Bash without awk.

array=()
while read -a line; do
    array+=("${line[4]} ${line[5]}")
done < <(df -h)
ephemient
  • 198,619
  • 38
  • 280
  • 391
0

You may use this:

eval array=( $(df -h | awk '{ printf("\"%s %s\" ", $5, $6) }') )
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134