例如 Python-sh, 它是一个使用 Go 语言的便捷调用 shell。
sh: export BUILD_ID=123 go: s = sh.NewSession().SetEnv("BUILD_ID", "123") sh: alias ll='ls -l' go: s = sh.NewSession().Alias('ll', 'ls', '-l') sh: (cd /; pwd) go: sh.Command("pwd", sh.Dir("/")).Run() sh: test -d data || mkdir data go: 如果 ! sh.Test("dir", "data") { sh.Command("mkdir", "data").Run() } sh: cat first second | awk '{print $1}' go: sh.Command("cat", "first", "second").Command("awk", "{print $1}").Run() sh: count=$(echo "one two three" | wc -w) go: count, err := sh.Echo("one two three").Command("wc", "-w").Output()
sh (在 Ubuntu 中): timeout 1s sleep 3 go: c := sh.Command("sleep", "3"); c.Start(); c.WaitTimeout(time.Second) # 默认的 SIGKILL go: out, err := sh.Command("sleep", "3").SetTimeout(time.Second).Output() # 设置会话超时并获取输出 sh: echo hello | cat go: out, err := sh.Command("cat").SetInput("hello").Output() sh: cat # 从标准输入读取 go: out, err := sh.Command("cat").SetStdin(os.Stdin).Output() sh: ls -l > /tmp/listing.txt # 将标准输出写入文件 go: err := sh.Command("ls", "-l").WriteStdout("/tmp/listing.txt") 如果需要保留 env 和 dir,最好创建一个会话
session := sh.NewSession() session.SetEnv("BUILD_ID", "123") session.SetDir("/")
session.Command("echo", "hello").Run()
session.ShowCMD = true
默认情况下,管道仅在最后一个命令以非零状态退出时才返回错误。不过,您也可以启用类似于 bash 的 pipefail 选项。在这种情况下,管道将返回错误。
暂无开放 Issues,或尚未同步最近议题。