我写了一个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
上单独执行时,将回显我需要的值,例如foo
,bar
,baz
。
如何捕获每个值,以便在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
答案 0 :(得分: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
}
$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.
希望这有帮助。