作業控制:如何將後台作業的輸出保存在變數中

作業控制:如何將後台作業的輸出保存在變數中

在 OSX 中使用 Bash。

我的腳本有以下兩行:

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}')

當我在第一行之後使用&(並行運行兩個 rsync 命令)時,我稍後的呼叫不會$nfiles返回任何內容。

代碼:

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

無法弄清楚發生了什麼事。我需要 2 個 rsync 同時運行。

答案1

您的範例不起作用的原因是因為後台命令是在子shell環境中執行的,因此 的值$nfiles將不可用(即:在您的範例程式碼中,它遺失了)。

解決此問題的簡單方法是使用臨時檔案。在下面的通用範例程式碼中,我用rsync更簡單的命令替換了管道,sleep並回顯任意數字:

# 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:
wait

# 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

相關內容