Reputation: 423
$ external_tool | grep -iE "id1|id2"
id1 Z55Hsh1abm
id2 sFXxu4KzkJbXab08UT
I have to store each id1 and id2 in separate variables mentioned below without executing external_tool
twice. Below is how I am doing now but that's not acceptable.
export VAR1=$(external_tool | grep -i id1 | awk '{print $2}')
export VAR2=$(external_tool | grep -i id2 | awk '{print $2}')
Desired output from above should be
$ echo $VAR1
Z55Hsh1abm
$ echo $VAR2
sFXxu4KzkJbXab08UT
How do I store them in separate variables and export them in env var?
Upvotes: 2
Views: 1105
Reputation: 22012
Would you please try the following:
#!/bin/bash
while read -r id val; do
if [[ $id = "id1" ]]; then
export var1=$val
elif [[ $id = "id2" ]]; then
export var2=$val
fi
done < <(external_tool | grep -iE "id1|id2")
echo "$var1"
echo "$var2"
id
.<(command)
expression is a process substitution and you can redirect the output of the command
to the while
loop.Please note that it is not recommended to use uppercases as a normal variable. That is why I've modified them as var1
and var2
.
Upvotes: 3
Reputation: 784948
You may get this done in a single call to external utility using process substitution using awk
:
read -r var1 var2 < <(external_tool | awk -v ORS=' ' '$1~/^(id1|id2)$/{print $2}')
# check variables
declare -p var1 var2
Upvotes: 2