doudou2121 2017-05-10 11:05 采纳率: 50%
浏览 2453
已采纳

在golang中使用os / exec在特定目录内执行命令

I want to run a command inside a particular directory.So here are 2 ways to do it.

command := exec.Command("echo *tar.gz | xargs -n1 tar zxf") 
command.Dir = pathFinal 
cmdErr := command.Run()

This is not working for me on the otherhand,

command := "cd "+pathFinal+"; "+"echo *tar.gz | xargs -n1 tar zxf" 
cmd := exec.Command("/bin/sh", "-c", command) 
cmdErr := command.Run()

This is working. I want to implement it the first way. I don't know why it is not working Second one throws an error

Failed to untar file: exec: "echo *tar.gz | xargs -n1 tar zxf": executable file not found in $PATH Am I missing something?

  • 写回答

1条回答 默认 最新

  • douqu2481 2017-05-10 12:30
    关注

    The first argument to Command specifies the executable to run. To run a shell pipe expression, execute a shell:

    command := exec.Command("/bin/sh", "-c", "echo *tar.gz | xargs -n1 tar zxf") 
    command.Dir = pathFinal 
    cmdErr := command.Run()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换