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


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


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

  • 写回答

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 c#:vsto,powerpoint的外接程序中换主题颜色
  • ¥15 状态机/汽车转向灯/Sateflow
  • ¥15 这个有点复杂 有没有人看看
  • ¥15 用python如何确定子孙元素在父元素中的位置
  • ¥15 obj文件滤除异常高程
  • ¥15 用mathematicas或者matlab计算三重积分
  • ¥15 Loop unrolling的runtime计算
  • ¥100 NVMe-oF的Target端,开启attr_offload后,测试失败。
  • ¥100 有偿照片马赛克去掉,保留原始数据
  • ¥15 c# winform http报错,如何解决?