Reputation: 497
I have a script like this that works fine:
#!/bin/bash
INBOUND=$(echo '5')
OUTBOUND=$(echo '10')
TOTAL=$(($INBOUND+$OUTBOUND))
echo "IN:$INBOUND OUT:$OUTBOUND T:$TOTAL"
Output: IN:5 OUT:10 T:15
Now suppose instead of echo 5
and echo 10
I have two commands that takes 10 seconds each to run.
I don't want my script to take 10+10 seconds to run and so I'm trying to use two sub-processes for each variable.
I thought whis would work:
#!/bin/bash
INBOUND=$(echo '5') &
OUTBOUND=$(echo '10')
wait
TOTAL=$(($INBOUND+$OUTBOUND))
echo "IN:$INBOUND OUT:$OUTBOUND T:$TOTAL"
But the first variable doesn't get a value and the output is: IN: OUT:10 T:10
How can I set each var in a separate process, so the script runs in 10 seconds instead of 10+10 ?
Upvotes: 1
Views: 607
Reputation: 532323
You need to use (temporary) files.
inbound_result=$(mktemp)
outbound_result=$(mktemp)
echo '5' > "$inbound_result" &
echo '10' > "$outbound_result" &
wait
read inbound < "$inbound_result"
read outbound < "$outbound_result"
total=$((inbound + outbound))
echo "IN: $inbound OUT:$outbound T:$total"
Upvotes: 3