tags:

views:

66

answers:

3

Hi all, 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?

+1  A: 

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
This is working well thank you
Steve Brown
You're welcome. If this was the right answer for you, you should upvote and mark as the accepted answer.
Brian Clements
You can omit the comma in the AWK command and set `IFS` to newline: `IFS=$'\n'` (don't forget `IFS=$OIFS` afterward).
Dennis Williamson
I've noticed that I sometimes get odd behavior when I use newline for ifs. I've gotten in the habit of using comma.
Brian Clements
A: 

You may use this:

eval array=( $(df -h | awk '{ printf("\"%s %s\" ", $5, $6) }') )
dtmilano
What's the `eval` for? Just leave off the extra quotes in the AWK command and do the array assignment directly.
Dennis Williamson
remove the eval and you'll get only one elem in the array...
dtmilano
A: 

You could do this in Bash without awk.

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