8

df does a great job for an overview. But what if I want to set a variable in a shell script to the number of bytes available on a disk?

Example:

$ df
Filesystem            1K-blocks     Used Available Use% Mounted on
/dev/sda             1111111111  2222222  33333333  10% /
tmpfs                  44444444      555  66666666   1% /dev/shm

But I just want to return 33333333 (bytes available on /), not the whole df output.

Ryan
  • 14,682
  • 32
  • 106
  • 179

7 Answers7

12

You may get exact number of bytes with df:

df -B1 / Filesystem 1B-blocks Used Available Use% Mounted on /dev/mapper/cl-root 32893632512 13080072192 18119061504 42% /

Odondon Labama
  • 129
  • 2
  • 3
  • This is the correct answer if you want the actual number of bytes (as I did) and not the number of 1024-sized blocks. Of course, you still have to parse it with awk or whatever, but that's trivial. Thank you! – jacderida Apr 23 '22 at 02:35
7

You may use awk,

df | awk '$1=="/dev/sda"{print $4}'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
6

Portably:

df -P /dev/sda1 | awk 'NR==2 {print $4}'

The -P option ensures that df will print output in the expected format, and will in particular not break the line after the device name even if it's long. Passing the device name as an argument to df removes any danger from parsing, such as getting information for /dev/sda10 when you're querying /dev/sda1. df -P just prints two lines, the header line (which you ignore) and the one data line where you print the desired column.

There is a risk that df will display a device name containing spaces, for example if the volume is mounted by name and the name contain spaces, or for an NFS volume whose remote mount point contains spaces. In this case, there's no fully portable way to parse the output of df. If you're confident that df will display the exact device name you pass to it (this isn't always the case), you can strip it:

df -P -- "$device" | awk -vn=${#device} 'NR==2 {$0 = substr($0, n+1); print $3}'
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
  • On my macbook pro, this worked for me to just give me the human readable version of what is available: `df -h | grep disk1s5 | awk '{print $4}'` – james-see Jan 07 '20 at 19:38
4

Only in Linux

df --output=avail
whoan
  • 8,143
  • 4
  • 39
  • 48
Alex Mantaut
  • 3,657
  • 3
  • 35
  • 45
3

You can use an awk

df | grep sda | awk '{print $4}'
ergonaut
  • 6,929
  • 1
  • 17
  • 47
1

You can query disk status with stat as well. To query free blocks on filesystem mounted at /:

stat -f -c '%f' /

To get the result in bytes instead of blocks, you can use shell's arithmetic:

echo $((`stat -f -c '%f*%S' /`))
Zouppen
  • 1,214
  • 11
  • 17
0

Very similar answers to the ones shown, but if you don't know the name of filesystem and are just looking for the total available space on the partition.

df -P --total | grep 'total' | awk '{print $4}'