如何正确地将参数传递给系统调用(git)?

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

How to pass arguments correctly to syscall (git)?

问题

我正在尝试通过调用syscall来克隆一个git仓库。(我知道有git2go,但那不是我想要的。我确实想要使用syscall

git, lookErr := exec.LookPath("git")

if lookErr != nil {
    fmt.Fprintf(os.Stderr, "%s\n", lookErr)
    os.Exit(126)
}

args := []string{"clone", "http://github.com/some/repo.git"}

var env = os.Environ()

execErr := syscall.Exec(git, args, env)

if execErr != nil {
  panic(execErr)
}

所以我想要执行的是git clone http://github.com/some/repo.git,手动执行这个命令是可以的。但是当我在上面的代码片段中以go方式运行时,git会报错:

git: 'http://github.com/some/repo.git' 不是一个git命令。请参阅'git --help'。

为什么git会将第二个参数解释为另一个命令?它应该是远程<repo> URL,即git clone [options] [--] <repo> [<dir>]

我该如何正确传递参数,以便git具有预期的行为?

英文:

I am trying to clone a git repository by calling git via syscall. (I know there is git2go but that's not what I want. I definitely want to do a syscall)

git, lookErr := exec.LookPath(&quot;git&quot;)

if lookErr != nil {
    fmt.Fprintf(os.Stderr, &quot;%s\n&quot;, lookErr)
    os.Exit(126)
}

args := []string{&quot;clone&quot;, &quot;http://github.com/some/repo.git&quot;}

var env = os.Environ()

execErr := syscall.Exec(git, args, env)

if execErr != nil {
  panic(execErr)
}

So what I want to execute is git clone http://github.com/some/repo.git and executing this manually works just fine. But when I run it in go like in the code snippet above, git fails with this:

> git: 'http://github.com/some/repo.git' is not a git command. See 'git --help'.

Why would git interpret the 2nd argument as another command? It is supposed to be the remote &lt;repo&gt; URL, git clone [options] [--] &lt;repo&gt; [&lt;dir&gt;].

How do I pass the arguments correctly so git has the expected behavior?

答案1

得分: 2

argv的第一个参数通常是程序的名称,所以只需将其添加在那里:

args := []string{git, "clone", "http://github.com/some/repo.git"}
var env = os.Environ()
if err := syscall.Exec(git, args, env); err != nil {
    panic(err)
}

另请参阅:os.Args 变量。

英文:

The first argument of argv is usually a program's name, so just add it there:

args := []string{git, &quot;clone&quot;, &quot;http://github.com/some/repo.git&quot;}
var env = os.Environ()
if err := syscall.Exec(git, args, env); err != nil {
    panic(err)
}

See also: os.Args variable.

huangapple
  • 本文由 发表于 2015年8月1日 21:14:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/31762246.html
匿名

发表评论

匿名网友

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

确定