I'm trying to output the amount of free disk space on the filesystem /example
.
If I run the command df -k /example
I can get good information about available disk space in kb but only by being human and actually looking at it.
I need to take this data and use it somewhere else in my shell script. I initially thought about using cut
but then my script wont be portable to other disks as free disk space will vary and cut will not produce accurate results.
How can I get output of just the free disk-space of example in kb?
This is another solution:
output:
You can use stat(2) command to display free blocks and also to find out how large each block is, e.g.
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:
Finally, to put this into a variable is just a matter of using backtick substitution (or $() as in the first answer):
To get the output of
df
to display the data in kb you just need to use the-k
flag:Also, if you specify a filesystem to
df
, you will get the values for that specific, instead of all of them: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:You can get the
Available
(4th column) for example withawk
orcut
(previously piping totr
tosqueeze-repeats
(-s
) for spaces):As always, if you want to store the result in a variable, use the
var=$(command)
syntax like this: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:Show interesting columns only
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.