【问题标题】:How to loop on array of string如何在字符串数组上循环
【发布时间】:2018-09-12 19:32:53
【问题描述】:

我有一个用 golang 实现的命令行工具,它工作正常。 我想执行一些应该提供字符串列表的命令

apps := $(shell fxt run apps)
apps:
    @echo $(apps) is called

在终端中,我在执行make 时看到以下内容(完全没问题)

[app1 app2] is called

由于命令fxt run apps返回字符串数组(var apps []string

我的问题是我如何循环 apps 变量?

命令返回的数据很好,但现在我需要获取这个列表(app1 ... appN)并循环它,我不清楚的问题,我怎样才能循环数组字符串?

特殊情况是如果在循环列表中我得到app7 应该如何在代码中进行分叉,例如 if(app7) 打印mvn clean install

示例。

对于每个应用程序(在应用程序列表中)我需要运行命令

go test ./...

但是对于需要运行的app7

mvn clean install

对于 app10

yarn

【问题讨论】:

  • 对不起,我不明白。如果您包含上面显示的 makefile 的实际输出,那么会更清楚,然后清楚地描述为什么该输出是错误的以及您希望看到什么输出。此外,最好指定您需要处理的任何特殊情况。
  • @MadScientist - 完成,请看一下
  • fxt 程序的输出是否包含方括号 ([])?如果你有更多元素,它会显示[app1 app2 app3 app4] is called吗?
  • @MadScientist - 是的,它看起来就像[app1 app2 app3 appN] is called

标签: linux go makefile gnu-make gnu


【解决方案1】:

您想在 make 本身或实际上正在执行 shell 的配方中运行您的循环?这两个都有!

备注:我将执行的命令替换为自己测试。这里我使用ls 来填充我的数组。

apps := $(shell ls)

#looping in make itself
$(foreach var,$(apps),$(info In the loop running with make: $(var)))

#loop in shell inside recipe 
go:
    @for v in $(apps) ; do \
        echo inside recipe loop with sh command: $$v ; \
    done

输出:

In the loop running with make: a
In the loop running with make: b
In the loop running with make: c
In the loop running with make: Makefile
inside recipe loop with sh command: a
inside recipe loop with sh command: b
inside recipe loop with sh command: c
inside recipe loop with sh command: Makefile

【讨论】:

  • In the loop running with make: [app In the loop running with make: app2]
  • 数组在那里,我怎么能省略数组[' and this ]`?
  • 即使我里面有100个应用程序,我也需要删除第一个和最后一个[]
  • 好吧,这不是一个新问题...:) 我没有编辑我的问题,在我写的问题中我有字符串数组,这就是这里的问题...跨度>
  • 但正如你所建议的,我会提出一个新问题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 2019-01-07
  • 1970-01-01
相关资源
最近更新 更多