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?

2
  • What do you want to do with the array after having it in bash ? I mean ... probably you can do that in awk ... Commented Oct 29, 2010 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 Commented Oct 29, 2010 at 22:26

3 Answers 3

10

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

OIFS=$IFS #save original
IFS=','
df -h | awk '{ print $5" "$6"," }'
Sign up to request clarification or add additional context in comments.

3 Comments

You're welcome. If this was the right answer for you, you should upvote and mark as the accepted answer.
You can omit the comma in the AWK command and set IFS to newline: IFS=$'\n' (don't forget IFS=$OIFS afterward).
I've noticed that I sometimes get odd behavior when I use newline for ifs. I've gotten in the habit of using comma.
1

You could do this in Bash without awk.

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

Comments

0

You may use this:

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

1 Comment

What's the eval for? Just leave off the extra quotes in the AWK command and do the array assignment directly.

Your Answer

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