How do I get results from background process linux shell scripts?… here is a solution to the problem.
How do I get results from background process linux shell scripts?
For example, suppose I want to count the number of lines of 10 large files and print the total number.
for f in files
do
#this creates a background process for each file
wc -l $f | awk '{print $1}' &
done
I’m trying something like this :
for f in files
do
#this does not work :/
n=$( expr $(wc -l $f | awk '{print $1}') + $n ) &
done
echo $n
Solution
I finally found a working solution using anonymous pipes and bash :
#!/bin/bash
# this executes a separate shell and opens a new pipe, where the
# reading endpoint is fd 3 in our shell and the writing endpoint
# stdout of the other process. Note that you don't need the
# background operator (&) as exec starts a completely independent process.
exec 3< <(./a.sh 2&1)
# ... do other stuff
# write the contents of the pipe to a variable. If the other process
# hasn't already terminated, cat will block.
output=$(cat <&3)