douhuan2101 2019-05-28 09:19
浏览 266


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.

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



  • ¥50 可视化界面构建,实现信息模块功能
  • ¥15 基于bert-base-chinese的中文文本处理
  • ¥15 高价求抖音抓包技术,抖音抓包无网络问题
  • ¥15 【matlab】已知功率谱密度反求时域信号
  • ¥15 mindspore项目_模型适配
  • ¥15 openstack使用cinder后,实例运行时分配的总空间不能大于ceph的总空间
  • ¥15 [pcl::PLYWriter::writeASCII] Error during opening (?鶂?)!
  • ¥15 得到XY两轴的数据如何绘制成圆,输入整形器
  • ¥29 PHP读取PDF文件添加多个数字签名
  • ¥25 联邦学习vgg修改最后一个全连接层报错(默认是1000个输出,我的改为11就报错,改为200就没问题)