英文:
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("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)
}
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 <repo>
URL, git clone [options] [--] <repo> [<dir>]
.
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, "clone", "http://github.com/some/repo.git"}
var env = os.Environ()
if err := syscall.Exec(git, args, env); err != nil {
panic(err)
}
See also: os.Args
variable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论