Check Free Disk Space for Current Partition in Bash

Check free disk space for current partition in bash

Yes:

df -k .

for the current directory.

df -k /some/dir

if you want to check a specific directory.

You might also want to check out the stat(1) command if your system has it. You can specify output formats to make it easier for your script to parse. Here's a little example:

$ echo $(($(stat -f --format="%a*%S" .)))

Use 'df -h' to check % remaining disk space of a specific folder

This command will give you percentage of /nas/home directory

df /nas/home | awk '{ print $4 }' | tail -n 1| cut -d'%' -f1

So basically you can use store as value in some variable and then apply if else condition.

var=`df /nas/home | awk '{ print $4 }' | tail -n 1| cut -d'%' -f1`
if(var>75){
#send email
}

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

Execute a command which will check if the disk space on somepartion is greater than 1 KB, return -1 else return 0

This may do:

df | awk 'END {print ($4<1024?"-1":"0")}'
0

You can change the number to any that fits your need.

END is used to get last line, instead of tail


To get it into an exit/return code do:

(exit $(df | awk 'END {print ($4<1024?"-1":"0")}')); echo "$?"

PS exit -1 will give 255

Get free space of HDD in linux

I think stat command should help. You can get the get the partitions from /proc/partitions.

Sample stat command output:

$ stat -f /dev/sda1
File: "/dev/sda1"
ID: 0 Namelen: 255 Type: tmpfs
Block size: 4096 Fundamental block size: 4096
Blocks: Total: 237009 Free: 236970 Available: 236970
Inodes: Total: 237009 Free: 236386


Related Topics



Leave a reply



Submit