Get Free Disk Space with Df to Just Display Free Space in Kb

Get free disk space with df to just display free space in kb?

To get the output of df to display the data in kb you just need to use the -k flag:

df -k

Also, if you specify a filesystem to df, you will get the values for that specific, instead of all of them:

df -k /example

Regarding the body of your question: you want to extract the amount of free disk space on a given filesystem. This will require some processing.

Given a normal df -k output:

$ df -k /tmp
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 7223800 4270396 2586456 63% /

You can get the Available (4th column) for example with awk or cut (previously piping to tr to squeeze-repeats (-s) for spaces):

$ df -k /tmp | tail -1 | awk '{print $4}'
2586456
$ df -k /tmp | tail -1 | tr -s ' ' | cut -d' ' -f4
2586456

As always, if you want to store the result in a variable, use the var=$(command) syntax like this:

$ myUsed=$(df -k /tmp | tail -1 | awk '{print $4}')
$ echo "$myUsed"
2586456

Also, from the comment by Tim Bunce you can handle long filesystem names using --direct to get a - instead, so that it does not print a line that breaks the engine:

$ df -k --direct /tmp
Filesystem 1K-blocks Used Available Use% Mounted on
- 7223800 4270396 2586456 63% /

Find size and free space of the filesystem containing a given file

If you just need the free space on a device, see the answer using os.statvfs() below.

If you also need the device name and mount point associated with the file, you should call an external program to get this information. df will provide all the information you need -- when called as df filename it prints a line about the partition that contains the file.

To give an example:

import subprocess
df = subprocess.Popen(["df", "filename"], stdout=subprocess.PIPE)
output = df.communicate()[0]
device, size, used, available, percent, mountpoint = \
output.split("\n")[1].split()

Note that this is rather brittle, since it depends on the exact format of the df output, but I'm not aware of a more robust solution. (There are a few solutions relying on the /proc filesystem below that are even less portable than this one.)

BASH 'df' command showing the same numbers for all directories?

You want to use the du command. df is used for measuring disk usage of a whole partition. Here is an example to determine the disk spaced used by a directory and all sub-directories:

du -sh /home/darwin

Display Disk Size and FreeSpace in GB

Try calculated properties. I would also add [math]::Round() to shorten the values:

gwmi win32_logicaldisk | Format-Table DeviceId, MediaType, @{n="Size";e={[math]::Round($_.Size/1GB,2)}},@{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}

n stands for name and e for expression. You could use the full names too, but it's a waste of space if you're writing multiple calculated Properties.



Related Topics



Leave a reply



Submit