Skip to content

Instantly share code, notes, and snippets.

@mosfet1kg
Forked from alwqx/diskusage.go
Created January 16, 2021 12:03
Show Gist options
  • Save mosfet1kg/cdbc71b54abfd2bb3d062063d07b5929 to your computer and use it in GitHub Desktop.
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`
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