Go 实战--go 语⾔中执⾏shell 脚本(Thewaytogo )
⽣命不⽌,继续go go go
接触linux 的⼈对shell ⼀定不陌⽣,君不见那些噼⾥啪啦敲的飞快的服务端程序猿都是在键⼊,ls cd cat 等。
何为shell ?
Simply put, the shell is a program that takes your commands from the keyboard and gives them to the operating system to perform. In the old days, it was the only user interface available on a Unix computer. Nowadays, we have graphical user interfaces (GUIs) in addition to command line interfaces (CLIs) such as the shell.
On most Linux systems a program called bash (which stands for Bourne Again SHell, an enhanced version of the original Bourne shell program, sh, written by Steve Bourne) acts as the shell program. There are several additional shell programs available on a typical Linux system. These include: ksh, tcsh and zsh.
Shell 是⼀个⽤C 语⾔编写的程序,它是⽤户使⽤Linux 的桥梁。Shell 既是⼀种命令语⾔,⼜是⼀种程
序设计语⾔。 Shell 是指⼀种应⽤程序,这个应⽤程序提供了⼀个界⾯,⽤户通过这个界⾯访问操作系统内核的服务。
os/exec package
go 中为我们提供了⼀个os/exec 包:⽤于运⾏外部的命令。
Cmd 结构其中, Stdout specify the process’s standard output
func Command
原型:
type Cmd struct { Path string Args []string Env []string Dir string Stdin io.Reader Stdout io.Writer Stderr io.Writer ExtraFiles []*os.File SysProcAttr *syscall.SysProcAttr Process *os.Process ProcessState *os.ProcessState }
1
2
3
4
56
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23func Command(name string , arg ...string ) *Cmd
1
作⽤:Command returns the Cmd struct to execute the named program with the given arguments. 例如:
cmd := exec.Command(“/bin/bash”, “-c”, “ls”)
cmd := exec.Command(“tr”, “a-z”, “A-Z”)
func (*Cmd) Run
作⽤:开始运⾏并等待结束。
这⾥需要注意Run 和Start 的区别:
Start starts the specified command but does not wait for it to complete.
开始运⾏不等待结束。
应⽤代码输出:
Linux 应⽤代码2
func (c *Cmd) Output() ([]byte , error)
1package main import ( "bytes" "fmt" "log" "os/exec" )func exec_shell(s string ) { cmd := exec.
Command("/bin/bash", "-c", s) var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { log.Fatal(err) } fmt.Printf("%s", out.String())}func main() { exec_shell("uname ")}
1
2
3
4
shell命令属于什么语言5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
这段代码⽤到了sync 包,之后会介绍的。package main import ( "fmt" "os/exec" "sync" "strings")func exe_cmd(cmd string , wg *sync.WaitGroup) { fmt.Println(cmd) parts := strings.Fields(cmd) out, err := exec.Command(parts [0],parts [1]).Output() if err != nil { fmt.Println("error occured") fmt.Printf("%s", err) } fmt.Printf("%s", out) wg.Done()}func main() { wg := new (sync.WaitGroup) commands := []string {"echo newline >> foo.o", "echo newline >> f1.o", "echo newline >> f2.o"} for _, str := range commands { wg.Add (1) go exe_cmd(str, wg) } wg.Wait()}
123456789101112131415161718192021222324252627282930
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论