Get the free space available in current directory in Bash
The output can be made a bit easier to parse by using the -P
option which will ensure that:
- 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.
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% /
In bytes:
df --output=avail -B 1 "$PWD" | tail -n 1
Human readable:
df --output=avail -h "$PWD" | tail -n 1
or
df --output=avail -B 1 "$PWD" |tail -n 1 | numfmt --to="iec"
or
df --output=avail -B 1 "$PWD" |tail -n 1 | numfmt --grouping