首页 > 解决方案 > 用于从文件创建数组并使用 curl URL 上的每个值的 Bash 脚本

问题描述

我正在编写一个 bash 脚本,我得到了一个 IP 列表,我想在 CURL 命令中一个一个地添加它们。例如,在名为 list.txt 的文件中给定列表

8.8.8.8
10.10.10.10
136.34.24.22
192.168.10.32

我想在 curl 命令上添加每个值

curl -k -u $user:$password "https://logservice/jobs" --data-urlencode 'search=search index=test $ARRAYVALUE | head 1' > output.txt

其中 $ARRAYVALUE 是要在命令中使用的 IP 地址。

我会很感激任何提示。

谢谢

标签: linuxbash

解决方案


如果我理解正确,你想:

  • 将“list.txt”的每一行映射到数组的一个项目
  • 循环遍历新创建的数组,将项目一一插入到您的命令调用中

考虑一下这个,大量评论的片段。特别mapfile注意变量是如何在curl调用中使用的,用引号括起来。

#!/bin/bash
# declare a (non-associative) array 
# each item is indexed numerically, starting from 0
declare -a ips
#put proper values here
user="userName"
password="password"
# put file into array, one line per array item
mapfile -t ips < list.txt

# counter used to access items with given index in an array
ii=0
# ${#ips[@]} returns array length 
# -lt makes "less than" check 
# while loops as long as condition is true
while [ ${ii} -lt ${#ips[@]} ] ; do 
  # ${ips[$ii]} accesses array item with the given (${ii}) index
  # be sure to use __double__ quotes around variable, otherwise it will not be expanded (value will not be inserted) but treated as a string
  curl -k -u $user:$password "https://logservice/jobs" --data-urlencode "search=search index=test ${ips[$ii]} | head -1" > output.txt
  # increase counter to avoid infinite loop
  # and access the next item in an array
  ((ii++))
done

您可以阅读GNU Bash 参考资料:Built- ins mapfile

您可以在GNU Bash 参考中阅读有关创建和访问数组的信息:数组

查看这篇关于.bash

我希望你发现这个答案有帮助。


推荐阅读