0

My aim is checking if there is still enough space on my disk, every time my script (bash) proceeds a step.

Running df; echo $? prints:

Dateisystem     1K-Blöcke    Benutzt Verfügbar Verw% Eingehängt auf
/dev/sdc4      1869858440 1680951776  93900284   95% /mnt/dd
0

The 0 is the result of that command. In my case, I only want 93900284 in a variable or as the result.

I already read man df.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Hert
  • 11
  • 2
  • 3

3 Answers3

2

df --output=avail /path/to/where/you/want/to/write | tail -n 1

BTW: bash 'returns' (in this case 0 == success) are exit codes, the way you phrase it it seems you try to capture that rather than the output. In that case, you might want to read this.

Wrikken
  • 69,272
  • 8
  • 97
  • 136
  • GNU's `df` isn't the only one that'll ever be run on the Linux kernel -- busybox runs on Linux too, after all; thus, it might not hurt to include an option that works with non-GNU tools. OTOH, if you pointed the OP at the source for the relevant numbers in sysfs, there'd be no dependency on any external tool at all. – Charles Duffy Oct 01 '16 at 20:02
  • Hehe, you know, I was looking at the sysfs option but I didn't know it OTOH, and got lazy, you correctly called me on that :) Voting to close as the duplicate you found. – Wrikken Oct 02 '16 at 07:31
1

You can use awk to extract suitable field from output:

BASH_VAR=`df | awk '/\/dev\/sda4/{print $4;}''`
fghj
  • 8,898
  • 4
  • 28
  • 56
  • 1
    `grep` followed by `awk` is rarely necessary - let `awk` select both the line and the field. – Mark Setchell Oct 01 '16 at 20:33
  • BTW, shell-local variables should typically have names with at least one lowercase character. POSIX specifies environment variables with meaning to the system or shell to always have all-uppercase names; using lowercase names for your own variables means you'll never overwrite something important by accident (a risk that exists because creating a shell variable with the same name as an environment variable overwrites the latter). See http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html – Charles Duffy Oct 02 '16 at 14:48
0

If what you want to do is display only available disk space, you can use the following command

 df -k /dev/sdc4 | tail -1 | awk '{print $4}'
yudori
  • 78
  • 1
  • 2
  • 10