将输入的命令行管道传递给bash解释器

huangapple go评论69阅读模式
英文:

Pipe input command line to bash interpreter

问题

func RunExtern(c *shell.Cmd) (string, os.Error) {
cmd := exec.Command("bash", "-c", c.Cmd()+" "+strings.Join(c.Args(), " "))
out, err := cmd.Output()

return string(out), err

}

英文:

I'm writing a small program with an interpreter, I would like to pipe any command that is not recognized by my shell to bash, and print the output as if written in a normal terminal.

func RunExtern(c *shell.Cmd) (string, os.Error) {	
    cmd := exec.Command(c.Cmd(), c.Args()...)
    out, err := cmd.Output()

    return string(out), err
}

this is what I've written so far, but it only executes a program with its args, I would like to send the whole line to bash and get the output, any idea how to do so ?

答案1

得分: 5

例如,要以列的形式列出目录条目,

package main

import (
	"exec"
	"fmt"
	"os"
)

func BashExec(argv []string) (string, os.Error) {
	cmdarg := ""
	for _, arg := range argv {
		cmdarg += `"` + arg + `" `
	}
	cmd := exec.Command("bash", "-c", cmdarg)
	out, err := cmd.Output()
	return string(out), err
}

func main() {
	out, err := BashExec([]string{"ls", "-C"})
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(out)
}
英文:

For example, to list directory entries in columns,

package main

import (
	"exec"
	"fmt"
	"os"
)

func BashExec(argv []string) (string, os.Error) {
	cmdarg := ""
	for _, arg := range argv {
		cmdarg += `"` + arg + `" `
	}
	cmd := exec.Command("bash", "-c", cmdarg)
	out, err := cmd.Output()
	return string(out), err
}

func main() {
	out, err := BashExec([]string{`ls`, `-C`})
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(out)
}

huangapple
  • 本文由 发表于 2011年12月22日 10:47:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/8598919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定