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.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!