Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

When I use df -h, I get the following output:

Filesystem Size Used Avail Use% Mounted on

/dev/mapper/VolGroup00-LogVol00 59G 2.2G 54G 4% /

/dev/sda1 122M 38M 78M 33% /boot

tmpfs 1.1G 0 1.1G 0% /dev/shm

                   11T  8.4T  2.1T  81% /storage4

                   15T  8.9T  5.9T  61% /storage1

/dev/mapper/patha 5.0T 255G 4.8T 5% /storage5_vol0

/dev/mapper/pathb 5.0T 195G 4.9T 4% /storage5_vol1

/dev/mapper/pathc 5.0T 608G 4.5T 12% /storage5_vol2

I want to write a script that gets the value of Avail column on a specific storage.

I used to use

df -k /storage_name | tail -1 | awk '{print $3}'

But the FileSystem column can have a value or not .. which would change the variable of my script from $3 to $4.

How can I get the Avail on a single command line even if there are no values on the previous columns?

share|improve this question
+1 interesting question. In case you do not get any answers here you might be interested in the separate unix.SE. Simply flag for a mod to migrate this question – Tobias Kienzler Mar 15 '11 at 15:46
Please don't cross-post. – Dennis Williamson Mar 15 '11 at 16:47
up vote 3 down vote accepted

Simply turn on POSIX compatible output (-P) to df:

$ df -Pk /dev/sda1 | tail -n 1 | awk '{print $4}'

That ensures that the format of each line is the same (no line feed after long device names).

share|improve this answer
Thx. That's exactly what I needed. – Diego Dias Mar 15 '11 at 15:58

Use -P option to df, to make sure output is normalized, and not splitted to many lines.

And, anyway - you can also always use $(NF-2) to print available column.

share|improve this answer
Thx. That's exactly what I needed. I chose Matt Jenkins answer just because he did it first. – Diego Dias Mar 15 '11 at 15:58

Work off the NF variable (number of fields). Something like :

df -k /storage_name|tail -1 |awk 'NF == 6 {print $3};NF == 5 {print $4}'

share|improve this answer
Instead he can just { print $( NF-2 ) } – user7385 Mar 15 '11 at 15:53
It works for the situation I have right now. But not for a generic one, where could be no values on more than one column. – Diego Dias Mar 15 '11 at 15:59
df -k /dev | tail -1 | sed s/"^[^0-9]*"// | awk '{print $3}'

Adding the sed will remove all non-digit characters from the beginning of the line. You may need to modify it a bit if you have digits in your filesystem name

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .