2
$ 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?

3
  • So what is your problem? What is client_secret and where is id2 gone? Commented Dec 1, 2020 at 3:42
  • sorry @tshiono its id2 really , my only problem is I can't run the tool again (meaning external_tool can only be run once) so I need to be able to get the output in the desired format. Commented Dec 1, 2020 at 3:51
  • Thank you for the prompt feedback. Your requirement is understood. Would you please test my answer? Commented Dec 1, 2020 at 4:04

2 Answers 2

3

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" 
  • The basic concept is to keep the id's as the output of the command and switch the variable to assign depending on the value of id.
  • The <(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.

Sign up to request clarification or add additional context in comments.

Comments

2

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 

1 Comment

This is also a acceptable solution in my case , I changed the last declare to got them in my own vars. but works perfectly in single line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.