Using Bash in OSX.

My script has these 2 lines:

nfiles=$(rsync -auvh --stats --delete --progress --log-file="$SourceRoot/""CopyLog1.txt" "$SourceTx" "$Dest1Tx" | tee /dev/stderr | awk '/files transferred/{print $NF}') &
nfiles2=$(rsync -auvh --stats --delete --progress --log-file="$SourceRoot/""CopyLog2.txt" "$SourceTx" "$Dest2Tx" | tee /dev/stderr | awk '/files transferred/{print $NF}')

When I use the & after the first line (to run the two rsync commands in parallel), my later call to $nfiles returns nothing.


osascript -e 'display notification "'$nfiles' files transferred to MASTER," & return & "'$nfiles2' transferred to BACKUP," & return & "Log Files Created" with title "Copy Complete"'

Can't figure out what's going on. I need the 2 rsyncs to run simultaneously.


The reason that your example will not work is because the background command is executed in a subshell environment, therefore the value of $nfiles will not be available (ie: in your sample code, it's lost).

One easy way around this problem would be to use a temporary file. In the generalized sample code below, I've replaced you rsync pipelines with simpler commands which sleep and echo an arbitrary number:

# use existing value of TMPDIR if exists, else set it to /tmp
: ${TMPDIR:=/tmp}

# ensure temporary file will be deleted on interrupt or error:
trap "rm -f $TMPDIR/nfiles.$$; exit 1" 1 2 3 15

# run the first command in background and save output to a temporary file:
(sleep 3; echo 1) > $TMPDIR/nfiles.$$ &

nfiles2=$(sleep 1; echo 2)

# wait for background command to complete:

# save temporary file data in variables:
nfiles=$(cat $TMPDIR/nfiles.$$)

# remove the temp files on normal exit:
rm -f $TMPDIR/nfiles.$$

# $nfiles and $nfiles 2 should now contain the desired data
echo nfiles=$nfiles
echo nfiles2=$nfiles2
| improve this answer | |
  • The way you create temporary files is insecure: a local user could use this to overwrite your own files. Use mktemp instead. – Gilles 'SO- stop being evil' Sep 30 '16 at 21:23
  • @Gilles Doh! I agree. I'll get to it tomorrow or feel free to edit. – RobertL Sep 30 '16 at 23:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.