简体   繁体   中英

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

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

For ex:

df| tail -n 1 | awk '{print $4}'

This command returns available space on root partition and this command returns 23% space on my disk.

I want it return -1 if the space is less than 1 KB else return 0

and we can not write sh file for this so i want 0 and -1 answer through the command

UPDATED it should exit with that return code means it should exit with returncode 0 or -1

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

Use stat to get the available blocks and the block size, create an expression and pipe into bc .

Here I'm testing it with a value of 10240 bytes on a couple of FS, one with less than that free and one with more:

$ stat -f /sys/fs/cgroup -c "(%a * %s >= 10240) - 1" | bc
-1
$ stat -f / -c "(%a * %s >= 10240) - 1" | bc
0

Adjust the 10240 to your wanted value in bytes .

Here's the conventional df output:

$ df /
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sda1       11440712 5517040   5319464  51% /
$ df /sys/fs/cgroup/
Filesystem     1K-blocks  Used Available Use% Mounted on
none                   4     0         4   0% /sys/fs/cgroup

The corresponding stat being based on:

$ stat -f / -c "%a * %s / 1024" | bc
5319464

Note that using this instead of awk to parse the output of df is less fragile to possible output format changes of df .

To set the exit code from a script, capturing the output looks ok:

#!/bin/bash
echo Testing $@

exit `stat -f $@ -c "(%a * %s >= 10240) - 1" | bc`

Note you get 255 and not -1 returned - but then -1 is out of range since exit codes can only be 0 to 255.

$ ./sizer.sh /sys/fs/cgroup/
Testing /sys/fs/cgroup/
$ echo $?
255
$ ./sizer.sh /
Testing /
$ echo $?
0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM