linux - 用于从文件创建数组并使用 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 地址。
我会很感激任何提示。
谢谢
解决方案
如果我理解正确,你想:
- 将“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
我希望你发现这个答案有帮助。
推荐阅读
- ios - 移动到另一个 UIViewController 时 UIViewcontroller 不释放内存
- javascript - PrimeNg 编辑器未显示 - Angular
- visual-studio - 如何移动和分支团队项目?
- mysql - golang update 现在用松鼠设置时间
- android - 如果 Activity 被销毁,我可以从 Activity 调用静态方法吗?
- acumatica - 在 acumatica 报告的 PictureBox 中使用 base64 编码图像?
- bokeh - 使用散景绘制支撑和阻力
- android - 在 ListView 中显示 Android 中的 Youtube 视频列表
- ajax - Google Contacts API:请求的资源上不存在“Access-Control-Allow-Origin”标头
- javascript - 不能将 Splice 与来自字符串切片的数组一起使用