doujuyang1764 2018-09-11 17:04
浏览 773
已采纳

Golang exec.Command()bash命令不起作用

I want to run the following bash command using golang's exec.Command()

ls > sample.txt

For this I write

_,err:=exec.Command("ls",">","sample.txt").Output()

But this doesn't seem to work. I know I can write to a file by using

exec.Command().StdoutPipe()

But I want to write sepcifically in that manner. Any idea how I can do it in golang?

</div>
  • 写回答

1条回答 默认 最新

  • doucongmishang2385 2018-09-11 17:13
    关注

    From the docs:

    Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells. The package behaves more like C's "exec" family of functions. To expand glob patterns, either call the shell directly, taking care to escape any dangerous input, or use the path/filepath package's Glob function. To expand environment variables, use package os's ExpandEnv.

    With that in hand, my best guess to what you're trying to do is running bash and passing your command as an argument to it:

    out, err := exec.Command("bash", "-c", cmd)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?