【问题标题】:Call function from within Bash for-loop and capture output?从 Bash for 循环中调用函数并捕获输出?
【发布时间】:2014-11-01 18:17:24
【问题描述】:

我写了一个 Bash 脚本

#!/usr/bin/env bash 
SEVEN_DAYS="$((1000 * 60 * 60 * 24 * 7))"
TODAY=$(($(gdate +'%s * 1000 + %N / 1000000')))
PAST_WEEK=$(($TODAY - $SEVEN_DAYS))

get-stuff() {
    stuff=$(curl -s localhost:8888/path/to/data | jq --raw-output '[.time_series_by_stuff[].counts | keys | .[]] | unique | sort | .[]')
    echo $stuff
    }

get-last-weeks-events-by-stuff() {
    for stuff in $(get-stuff); do
    result=$(curl -s localhost:8888/path/to/$stuff/_search -d "{\"query\":\"range\":{\"ingestDate\":{ \"gte\":$PAST_WEEK}}}" | jq 'hits.total')
    echo $stuff
    echo $result
    done
}

在命令行get-stuff 上单独执行时,将回显我需要的值,例如foobarbaz

如何捕获每个值,以便它们可以在 get-last-weeks-events-by-stuff 内的 curl 命令中正确展开?

我应该创建一个像

这样的 tmp 变量吗?
get-last-weeks-events-by-stuff() {
        for stuff in $(get-stuff); do
        tmp=$stuff
        result=$(curl -s localhost:8888/path/to/$tmp ... 

最终,当我调用get-last-weeks-events-by-stuff 时,它应该会产生类似

的输出

foo 12 bar 15

【问题讨论】:

  • 你的风格很奇怪。在get-stuff 中,您不需要变量stuffecho $stuffcurl ... | jq ... 就足够了——除非你依赖路径名扩展,但我对此表示怀疑。此外,函数名中的连字符……也很奇怪。不要这样做。
  • 循环是否遍历get-stuff返回的所有值?以bash -x <script> 身份运行脚本可能会有所帮助。

标签: bash for-loop curl


【解决方案1】:

将 IFS 环境变量更改为在 , 而不是空格上拆分。

get-last-weeks-events-by-stuff() {
  IFS=,
  for stuff in $(get-stuff); do
    result=$(curl -s localhost:8888/path/to/$stuff/_search -d "{\"query\":\"range\":{\"ingestDate\":{ \"gte\":$PAST_WEEK}}}" | jq 'hits.total')
    echo $stuff
    echo $result
  done
  unset IFS
}

根据Linux Documentation Project

$IFS

    internal field separator

    This variable determines how Bash recognizes fields, or word boundaries, when it interprets character strings.

    $IFS defaults to whitespace (space, tab, and newline), but may be changed, for example, to parse a comma-separated data file. Note that $* uses the first character held in $IFS. See Example 5-1.

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 2013-05-10
    • 2018-05-21
    相关资源
    最近更新 更多