Last active
February 14, 2023 06:15
-
-
Save wuriyanto48/67ce6439ce168ef70a22aa71cf0d1440 to your computer and use it in GitHub Desktop.
Golang os/exec: execute df command
This file contains hidden or 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
package main | |
import ( | |
"fmt" | |
"io" | |
"os" | |
"os/exec" | |
"regexp" | |
"strings" | |
"encoding/json" | |
) | |
func main() { | |
dfPath, err := exec.LookPath("df") | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
cmd := exec.Command(dfPath, "/") | |
outPipe, err := cmd.StdoutPipe() | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
err = cmd.Start() | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
b, err := io.ReadAll(outPipe) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
ss := strings.Split(string(b), "\n") | |
if len(ss) >= 2 { | |
headers := ss[0] | |
values := ss[1] | |
fmt.Println(headers) | |
fmt.Println(values) | |
headerSplitted, err := split(headers) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
valueSplitted, err := split(values) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
// the length of headerSplitted must be equal to valueSplitted | |
headerSplitted = headerSplitted[:len(valueSplitted)] | |
jsonMap := make(map[string]string) | |
for i := 0; i < len(headerSplitted); i++ { | |
jsonMap[headerSplitted[i]] = valueSplitted[i] | |
} | |
jsonBytes, err := json.Marshal(jsonMap) | |
if err != nil { | |
fmt.Println("error:", err) | |
} else { | |
fmt.Println(string(jsonBytes)) | |
} | |
} | |
err = cmd.Wait() | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
} | |
// split function | |
func split(text string) ([]string, error) { | |
re, err := regexp.Compile(`\s+|\s+$`) | |
if err != nil { | |
return nil, err | |
} | |
result := re.Split(text, -1) | |
return result, nil | |
} | |
// output | |
// {"1K-blocks":"263174212","Available":"185765072","Filesystem":"/dev/sdd","Mounted":"/","Use%":"26%","Used":"63970984"} | |
// [Filesystem 512-blocks Used Available Capacity iused ifree %iused Mounted on /dev/disk3s1s1 1942700360 30677032 1352366864 3% 575614 4293938969 0% / ] | |
// [Filesystem 1K-blocks Used Available Use% Mounted on /dev/sdd 263174212 63969812 185766244 26% / ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment