Go语言学习日记【十三】GOLANG调用SHELL命令
原创
©著作权归作者所有:来自51CTO博客作者wx6347c4235109b的原创作品,请联系作者获取转载授权,否则将追究法律责任
// go调用外部命令,并在运行过程中传递参数
// hello.go
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, What's your favorite number?")
var i int
var j int
fmt.Scanf("%d", &i)
fmt.Println("1 Ah I like ", i, " too.")
fmt.Scanf("%d", &j)
fmt.Println("2 Ah I like ", j, " too.")
}
// 调用hello.go
package main
import (
"os"
"os/exec"
)
func main() {
cmd := exec.Command("go", "run","hello.go")
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Run()
}
package main
import (
"fmt"
"os/exec"
)
func main(){
var cmd *exec.Cmd
v := "/dev/sdb1"
com = fmt.Sprintf("mount -l | grep %s | cut -d ' ' -f 3",v)
cmd = exec.Command("/bin/bash","-c",com)
out,err := cmd.CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
}
package main
import (
"fmt"
"os/exec"
"strings"
"bytes"
)
func main() {
cmd:=exec.Command("sh","-c","ps aux|grep 'cli -m server'|grep Sl")
stdout:=&bytes.Buffer{}
cmd.Stdout=stdout
cmd.Run()
fmt.Println(len(strings.Split(strings.TrimRight(stdout.String(),"\n"),"\n")))
fmt.Println(strings.Split(strings.TrimRight(stdout.String(),"\n"),"\n"))
}