golang无法在终端上运行的exec命令 [英] golang failed exec command that works in terminal

查看:455
本文介绍了golang无法在终端上运行的exec命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用exec包运行mv命令时出现错误.

I am getting an error when I try to use the exec package to run a mv command.

以下是我要执行的操作的示例:

Here is an example of what I am trying to do:

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

cmd.Run()

err返回以下内容 exit status 1

err returns the following exit status 1

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

当我更改此行时,我实际上可以使脚本工作:

I can actually get the script to work when I change this line:

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

到以下:

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

该命令可以成功运行并成功移动文件,但不能使用通配符.在命令中似乎没有将星号用作通配符.这是为什么?还有其他在GO中使用通配符的方法吗?如果没有,那么我还能如何将所有文件从source-dir递归移动到dest-dir?

The command works and moves the file successfully but using the wildcard doesn't work. It appears that the asterisk isn't being used as a wildcard in the command. Why is that? Is there another way to use wildcards in GO? If not then how else would I be able to recursively move all files from the source-dir to the dest-dir?

谢谢

推荐答案

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

When you type the command at the shell, the shell takes ./source_dir/* and replaces it with a list of all of the files that match, one per argument. The mv command sees a list of filenames, not a wildcard.

您需要做的就是自己做同样的事情(使用 filepath.Glob 返回匹配文件的[]string),或调用外壳程序使其能够完成工作(使用exec.Command("/bin/sh", "-c", "mv ./source_dir/* ./dest_dir")).

What you need to do is either do the same thing yourself (using filepath.Glob which returns a []string of matching files), or to invoke the shell so that it can do the work (using exec.Command("/bin/sh", "-c", "mv ./source_dir/* ./dest_dir")).

这篇关于golang无法在终端上运行的exec命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆