AWK output to bash array

I am trying to put the contents of a simple command into a bash array, but I have a few problems.

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

gives the percentage used on file systems on my system the output is as follows:

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

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

However, when I print 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 forms an array based on spaces, not line breaks, how can I fix this?

+6
arrays bash awk
source share
3 answers

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

 OIFS=$IFS #save original IFS=',' df -h | awk '{ print $5" "$6"," }' 
+9
source share

You can do it in Bash without awk.

 array=() while read -a line; do array+=("${line[4]} ${line[5]}") done < <(df -h) 
+1
source share

You can use this:

 eval array=( $(df -h | awk '{ printf("\"%s %s\" ", $5, $6) }') ) 
0
source share

All Articles