Home > front end >  How to assign multiple variables in parallel in shell
How to assign multiple variables in parallel in shell

Time:07-02

ATM my current thoughts are, to do it like this:

a_NODE=$(node -v) &
a_NPM=v$(npm -v) &
a_YARN=v$(yarn -v) &
a_CURL=v$(curl --version | head -n 1 | awk '{ print $2 }') &
wait
echo "Node:             $a_NODE"
echo "NPM:              $a_NPM"
echo "YARN:             $a_YARN"
echo "curl:             $a_CURL"

But this actually skips all the variable definitions and prints empty version strings. AFAIK the wait command should make the script wait untill all of the varbiables are set and just then go over to printing - but it doesn't.

CodePudding user response:

Background commands run in subshells, so the variable assignments aren't in the original shell process.

Redirect the outputs to files, and read those files in the main shell.

node -v > /tmp/node.$$ &
npm -v > /tmp/npm.$$ &
yarn -v > /tmp/yarn.$$ &
curl --version | head -n 1 | awk '{ print $2 }' > /tmp/curl.$$ &
wait
a_NODE=$(</tmp/node.$$)
a_NPM=$(</tmp/npm.$$)
a_YARN=$(</tmp/yarn.$$)
a_CURL=$(</tmp/curl.$$)
rm -f /tmp/{node,npm,yarn,curl}.$$
  • Related