How to get the current free disk space in Bash?
Asked Answered
C

3

8

I'm running some operations which constantly eat up my disk space. For this reason I want my computer to make a sound when disk space is running below 2GB. I know I can get an output listing the free diskspace by running df -h:

Filesystem                                      Size   Used  Avail Capacity   iused     ifree %iused  Mounted on
/dev/disk1                                     112Gi  100Gi   12Gi    90%  26291472   3038975   90%   /
devfs                                          191Ki  191Ki    0Bi   100%       663         0  100%   /dev
map -hosts                                       0Bi    0Bi    0Bi   100%         0         0  100%   /net
map auto_home                                    0Bi    0Bi    0Bi   100%         0         0  100%   /home

but I can't use this output in an if-then statement so that I can play a sound when the Available free space drops below 2GB.

Does anybody know how I can get only the Available space instead of this full output?

Chinaware answered 13/1, 2014 at 8:51 Comment(0)
M
9

This was the only portable way (Linux and Mac OS) in which I was able to get the amount of free disk space:

df -Pk . | sed 1d | grep -v used | awk '{ print $4 "\t" }'

Be aware that df from Linux is different than the one from Mac OS (OS X) and they share only a limited amount of options.

This returns the amount of free disk space in kilobytes. Don't try to use a different measure because they options are not portable.

Memphis answered 19/8, 2016 at 13:37 Comment(0)
B
4

First, the available disk space depends on the partition/filesystem you are working on. The following command will print the available disk space in the current folder:

TARGET_PATH="."
df -h "$TARGET_PATH"  | awk 'NR==2{print $4}'

TARGET_PATH is the folder you are about writing to. df automatically detects the filesystem the folder belongs to.

Brigham answered 13/1, 2014 at 8:56 Comment(3)
Dropping -h from df options would help here: df . | awk 'NR==2{if($4<=2*1024*1024) print "Available space < 2 GB\a"}'Stool
Oh, yes. I didn't saw the > 2GB restriction .Brigham
Or even $ df --output=avail . | awk 'NR==2 && $0 <= 2 * 2**20 { print "Available space <= 2 GB\a" }'.Annunciata
A
-1
#!/bin/bash
Check_space() { 
    set -e
    cd
    Home=$PWD
    reqSpace=100000000
    SPACE= df "$Home"
    if [[ $SPACE -le reqSpace ]]
    then
    $SPACE
    echo "Free space on  " 
    fi
}
Check_space
Anthocyanin answered 16/7, 2020 at 7:23 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Quiescent

© 2022 - 2024 — McMap. All rights reserved.