dsfdsf46465 2015-07-17 01:36
浏览 148
已采纳

golang无法在终端上运行的exec命令

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 returns the following exit status 1

output returns this 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")

to the following:

cmd := exec.Command("mv", "./source-dir/file.txt", "./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?

Thanks

  • 写回答

1条回答 默认 最新

  • doulu8537 2015-07-17 01:40
    关注

    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.

    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")).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重