OSコマンドを実行する
環境
- macOS Monterey : 12.6.1
- iproute2macをbrewでインストール済み
コード実行
package.go
package main
import (
"fmt"
"os/exec"
)
const defaultGw = "172.22.0.1"
func main() {
pingCmd(defaultGw)
fmt.Println("-----")
catCmd("golang.txt")
fmt.Println("-----")
lsCmd()
fmt.Println("-----")
ipAddr()
}
func pingCmd(addr string) {
result, err := exec.Command("ping", addr, "-c3", "-i0.5").CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(result))
}
func catCmd(f string) {
result, err := exec.Command("cat", f).CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(result))
}
func lsCmd() {
result, err := exec.Command("ls", "-al").CombinedOutput()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(result))
}
func ipAddr() {
result, _ := exec.Command("ip", "addr").CombinedOutput()
fmt.Println(string(result))
}
実行結果
% go run ./execCmd.go
PING 172.22.0.1 (172.22.0.1): 56 data bytes
64 bytes from 172.22.0.1: icmp_seq=0 ttl=64 time=19.265 ms
64 bytes from 172.22.0.1: icmp_seq=1 ttl=64 time=3.376 ms
64 bytes from 172.22.0.1: icmp_seq=2 ttl=64 time=197.188 ms
--- 172.22.0.1 ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 3.376/73.276/197.188/87.859 ms
-----
Go is an open source programming language that makes it simple to build secure, scalable systems.
- An open-source programming language supported by Google
- Easy to learn and great for teams
- Built-in concurrency and a robust standard library
- Large ecosystem of partners, communities, and tools
-----
total 32
drwxr-xr-x 6 masashi staff 192 12 11 20:01 .
drwxr-xr-x 9 masashi staff 288 12 11 20:01 ..
-rw-r--r-- 1 masashi staff 620 12 11 20:01 calculation.go
-rw-r--r-- 1 masashi staff 796 12 11 20:01 execCmd.go
-rw-r--r-- 1 masashi staff 304 12 11 20:01 golang.txt
-----
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
inet 127.0.0.1/8 lo0
inet6 ::1/128
inet6 fe80::1/64 scopeid 0x1
*省略