golang failed exec命令在终端中工作

Joe*_*984 7 go

我尝试使用该exec包运行mv命令时收到错误.

这是我想要做的一个例子:

cmd := exec.Command("mv", "./source-dir/*", "./dest-dir")
output, err := cmd.CombinedOutput()

cmd.Run()
Run Code Online (Sandbox Code Playgroud)

错误返回以下内容 exit status 1

输出返回此 mv: rename ./source-dir/* to ./dest-dir/*: No such file or directory

当我改变这一行时,我实际上可以让脚本工作:

cmd := exec.Command("mv", "./source-dir/*", "./dest-dir")

以下内容:

cmd := exec.Command("mv", "./source-dir/file.txt", "./dest-dir")

该命令工作并成功移动文件,但使用通配符不起作用.似乎星号未在命令中用作通配符.这是为什么?还有另一种在GO中使用通配符的方法吗?如果没有那么我怎么能递归地将所有文件从?移动source-dirdest-dir

谢谢

hob*_*bbs 19

当您在shell中键入命令时,shell ./source_dir/*会将其替换为匹配的所有文件的列表,每个参数一个.该mv命令查看文件名列表,而不是通配符.

你需要做的是自己做同样的事情(使用返回匹配文件的filepath.Glob[]string),或者调用shell以便它可以完成工作(使用exec.Command("/bin/sh", "-c", "mv ./source_dir/* ./dest_dir")).