Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I know df -h and pwd, but it seems a little complex for the regex matching part. Any ideas?

share|improve this question
1  
Did you mean du -h? –  jweyrich Jan 18 '11 at 7:11
add comment

2 Answers

up vote 6 down vote accepted

The output can be made a bit easier to parse by using the -P option which will ensure that:

  1. The information about each file system is always printed on exactly one line; a mount device is never put on a line by itself. This means that if the mount device name is more than 20 characters long (e.g., for some network mounts), the columns are misaligned.

This makes it much easier to get just the free space available:

$ df -Ph . | tail -1 | awk '{print $4}'

(-h uses megabytes, gigabytes and so on. If your system doesn't have it, use -k for kilobytes only.)

If we pass df a path, it is only going to return 2 rows: a header row and then the data about the file system that contains the path. We can use tail to grab just the second row. We know that the space available is in the 4th column, so we grab that with awk. This all could be done with awk:

$ df -Ph . | awk 'NR==2 {print $4}'

or many other sets of filters.

share|improve this answer
    
You can optimize your command by using the environment variable $PWD instead of using command substitution and removing the need for tail: df -Ph $PWD | awk 'NR==2{print $4}' –  SiegeX Jan 18 '11 at 4:17
    
@SiegeX: I agree doing it all in awk is better. I included the longer command because I wanted to have an example of how one can construct a chain of simple commands to do something more complicated. I've updated the answer to include your improvement. –  Steven D Jan 18 '11 at 4:41
    
-P is standard (the P is for POSIX). But -h is a GNU extension (also existing on some other systems, but e.g. on OpenBSD it's incompatible with -P). –  Gilles Jan 18 '11 at 22:55
add comment

How about doing df -h .. This will give you the available free space of the partition your current working directory is in.

A small example:

 /usr/local/nagios/libexec # df -h .
 Filesystem            Size  Used Avail Use% Mounted on
 /dev/mapper/vg00-lvol1
                       9.9G  6.1G  3.4G  65% /
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.