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

半世苍凉 提交于 2019-11-28 20:21:45
fedorqui

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% /

You can use stat(2) command to display free blocks and also to find out how large each block is, e.g.

stat -f --printf="%a %s\n" /

will display number of free blocks (%a) on a given file system (/) followed by a block size (%s). To get size in kB, you can use bc(1) command as in the following example:

stat -f --printf="%a * %s / 1024\n" / | bc

Finally, to put this into a variable is just a matter of using backtick substitution (or $() as in the first answer):

SOMEVAR=`stat -f --printf="%a * %s / 1024\n" / | bc`

Show interesting columns only

 df /example --total -k -h  --output=source,avail
  • --total = grand total at the end
  • -k = block size 1K
  • -h = human readable
  • --output=[FIELD_LIST] column list to show separated by ","

Not totally standard (I have seen --output just in Ubuntu man pages), in this case Awk and others just to remove columns are not necessary.

This is another solution:

df --output=avail -m /example | tail -1

output:

6415

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!