golang failed exec命令在终端中工作

时间:2015-07-17 01:36:08

标签: go

当我尝试使用exec包来运行mv命令时,我收到错误。

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

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

cmd.Run()

错误返回以下内容 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-dir移动到dest-dir

由于

1 个答案:

答案 0 :(得分:15)

当你在shell上输入命令时,shell会取./source_dir/*并用一个匹配的所有文件的列表替换它,每个参数一个。 mv命令查看文件名列表,而不是通配符。

你需要做的是自己做同样的事情(使用filepath.Glob返回匹配文件的[]string),或者调用shell以便它可以完成工作(使用{ {1}})。

相关问题