2019-05-28 09:19
浏览 230


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 {

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. (

    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.

    打赏 评论

相关推荐 更多相似问题