使用sed在文本文件中循环一个curl命令



我有一个curl命令,将通过GitHub运行程序运行,文件export.sh看起来像:

while read -r auth0 &&  read -r roles <&3; do
curl --request POST 
--url 'https://YOUR_DOMAIN/api/v2/users/USER_ID/roles' 
--header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' 
--header 'cache-control: no-cache' 
--header 'content-type: application/json' 
--data '{ "roles": [ "ROLE_ID" ] }'
done < final-user-id.txt 3<final-id.txt

我有一个文件final-user-id.txt,它是这样的:

Jack
Amy
Colin

我还有一个文件final-id.txt:

role_1
role_2
role_3

我想以这样一种方式运行export.sh,每次它从final-user-id.txt中获取一个新变量并将其替换为auth0,"ROLE_ID"被替换为final-id.txt的内容,因此第一个输出将是:

while read -r auth0 &&  read -r roles <&3; do
curl --request POST 
--url 'https://YOUR_DOMAIN/api/v2/users/Jack/roles' 
--header 'authorization: Bearer MGMT_API_ACCESS_TOKEN' 
--header 'cache-control: no-cache' 
--header 'content-type: application/json' 
--data '{ "roles": [ "role_1" ] }'
done < final-user-id.txt 3<final-id.txt

依此类推,取决于变量的数量

这样如何:

#!/usr/bin/env bash
while IFS= read -r auth0 && IFS= read -r roles <&3; do
echo curl --request POST 
--url "https://YOUR_DOMAIN/api/v2/users/$auth0/roles" 
--header "authorization: Bearer MGMT_API_ACCESS_TOKEN" 
--header "cache-control: no-cache" 
--header "content-type: application/json" 
--data "{ 'roles': [ '$roles'] }"
done < final-user-id.txt 3<final-id.txt

输出
curl --request POST --url https://YOUR_DOMAIN/api/v2/users/Jack/roles --header authorization: Bearer MGMT_API_ACCESS_TOKEN --header cache-control: no-cache --header content-type: application/json --data { 'roles': [ 'role_1'] }
curl --request POST --url https://YOUR_DOMAIN/api/v2/users/Amy/roles --header authorization: Bearer MGMT_API_ACCESS_TOKEN --header cache-control: no-cache --header content-type: application/json --data { 'roles': [ 'role_2'] }
curl --request POST --url https://YOUR_DOMAIN/api/v2/users/Colin/roles --header authorization: Bearer MGMT_API_ACCESS_TOKEN --header cache-control: no-cache --header content-type: application/json --data { 'roles': [ 'role_3'] }

  • 虽然我建议为final-user-id.txt使用不同的fd,只是以防curl使用/消费stdin

  • 如果您对输出满意,请删除echo


由于您使用的是@DennisWilliamson所提到的bash,因此内置的read命令具有-u标志。所以第一行可以写成:

while IFS= read -ru3 auth0 && IFS= read -ru4 roles ; do

最后一行应该这样写:

done 3<final-user-id.txt 4<final-id.txt

最新更新