-
-
Save mosfet1kg/cdbc71b54abfd2bb3d062063d07b5929 to your computer and use it in GitHub Desktop.
calculate disk usage in golang (Linux only) by parse output of command `df`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import( | |
"fmt" | |
"strconv" | |
"strings" | |
"os/exec" | |
"log" | |
) | |
func main() { | |
out, _ := exec.Command("df", "-P").Output() | |
ret, err := parseDfOutput(string(out)) | |
if err != nil { | |
log.Println(err) | |
} | |
fmt.Println(ret) | |
} | |
func parseDfOutput(out string) (float64, error) { | |
outlines := strings.Split(out, "\n") | |
l := len(outlines) | |
var total, used float64 = 0, 0 | |
for _, line := range outlines[1:l-1] { | |
parsedLine := strings.Fields(line) | |
t, err := strconv.ParseFloat(parsedLine[1], 64) | |
if err != nil { | |
return 0, err | |
} | |
u, err := strconv.ParseFloat(parsedLine[2], 64) | |
if err != nil { | |
return 0, err | |
} | |
total += t | |
used += u | |
} | |
return used/total, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment