I am trying to write a bash script that echoes values of 2 variables in parallel as part of an experiment before writing a shell script that generates files with numbers appended to them in parallel for a project of mine.
Here is the shell script:
#!/bin/bash
value1=0
value2=1
for i in $(seq 1 2); do
echo "Value 1 : " $((++value1)) &
echo "Value 2 : " $((++value2))
wait
echo "Wait"
done
And here is the output I get:
Value 2 : 2
Value 1 : 1
Wait
Value 2 : 3
Value 1 : 1
Wait
I know about GNU parallel and xargs but I don't want to use them.
I would like to know why 'value2' gets printed first and why 'value1' never gets incremented.
&?value1never gets incremented because the background process runs in a sub shell, where any changes made to values don't get reported back to the parent shell. Andvalue2probably gets printed first because the shell handles the next line of execution before the subshell has managed to get its thoughts in order and produce output, but that order is not guaranteed. The two processes are running in parallel, and either could win the race to echo.value1. The main thread of execution remains while the backgrounded process is forked off as a separate shell. Imagine if thevalue1++took a while to process. At what point in the execution of the main script would you expect that variable to change, and what would actually cause it to change? What if other lines of the script were using and changing that variable?kill) to the main process which would execute atrap. Or you could send results back through a named pipe. Of course, there may be another way to parallelize whatever it is you're trying to do; I don't have enough info to make a recommendation.