Lets say I have the following file named "test"
which contains:
[a1b2c3]=test1.xyz
[d4e5f6]=test2.xyz
[g7h8i9]=test3.xyz
...
Which is about 30 lines long. I would want to assign
a1b2c3
d4e5f6
g7h8i9
into an array named array how would I do it?
with bash 3.1 this would be my attempt
declare -a array
while read -r line;
do
array =("$(echo "$line")")
done < test
But it seems that I need to upgrade my bash to 4 or 5 for declarative arrays. So the question would be, how do I separate specifically get the values inside the brackets per line to be assigned as different elements in an array array
This array values would be used in a curl script which should produce a file with the name of the values associated with it.
for i in "${array[@]}"
do
curl -X GET "https://api.cloudflare.com/client/v4/zones/$i/dns_records?" \
-H "X-Auth-Email: $X-Auth-Email" \
-H "X-Auth-Key: X-Auth-Key" \
-H "Content-Type: application/json" \
-o "${array[@]}.txt"
done
so the expectation is that curl -X GET "https://api.cloudflare.com/client/v4/zones/a1b2c3/dns_records?
would be run and an output file named test1.xyz.txt
would be produced containing the dns records of the said link. Which goes for the next line and test2.xyz.txt
and so on and so forth.
CodePudding user response:
Assuming the string inside the brackets is composed of alphanumeric characters, would you please try:
#!/bin/bash
while IFS== read -r name val; do
name=${name#[} # remove left square bracket
name=${name%]} # remove right square bracket
printf -v "var_$name" %s "$val" # assign e.g. var_a1b2c3 to test1.xyz
done < test
for var in "${!var_@}"; do
name=${var#var_} # retrieve e.g. a1b2c3 by removing var_
curl -X GET "https://api.cloudflare.com/client/v4/zones/$name/dns_records?" \
-H "X-Auth-Email: $X-Auth-Email" \
-H "X-Auth-Key: X-Auth-Key" \
-H "Content-Type: application/json" \
-o "${!var}.txt"
done
- As an indirect variable assignment,
printf -v varname value
works. - As an indirect variable referencing,
"${!var_@}"
is expanded to a list of variable names which starts withvar_
. ${!var}
refers to the value whose variable name is expressed by "$var".
Tested with bash-3.2.57. Hope it will be interoperable with bash-3.1.