douhuan2101 2019-05-28 09:19
浏览 266
已采纳

使用golang从命令行将输入读取到Shell脚本exec中

I am using go to run a shell script using exec.command like below and I want to take an input argument using command line say i, and my output should be based on i, how would I do that?

i := os.Args[1:2]
out, err := exec.Command("bash", "-c", "tail -n 1 /var/log/apache2/access.log | awk '{print $i/1024}' >> mem_usage.csv").Output()
if err != nil {
    fmt.Println(err.Error())
    return
 }

How could I use that i in the shell script?

Without i it works fine i.e if I put $1 or $2 it works fine but I want user to give me the position of i and then calculate accordingly.

  • 写回答

1条回答 默认 最新

  • dqm4675 2019-05-28 09:22
    关注

    You need to format the exec-command string accordingly.

    So ie:

    fmt.Sprintf("awk '{print $%d/1024}'", i)

    This gives: awk '{print $1/1024}' for i = 1 and awk '{print $2/1024}' for i = 2

    fmt.Sprintf takes a format string and the arguments to pass into this string and returns the formatted string. (https://golang.org/pkg/fmt/#Sprintf)

    And this needs to be inserted into your exec-command:

    i := 2
    awkPart := fmt.Sprintf("awk '{print $%d/1024}'", i)
    out, err := exec.Command("bash", "-c", "tail -n 1 /var/log/apache2/access.log | "+awkPart+" | tee -a mem_usage.csv").Output()
    

    You should maybe try to disassemble your command a bit more for maintainabilty, but that's not part of the question.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器