ジョブ制御:バックグラウンドジョブの出力を変数に保存する方法

ジョブ制御:バックグラウンドジョブの出力を変数に保存する方法

OSXでBashを使用してください。

私のスクリプトには2つの行があります。

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

最初の行以降に使用すると&(2つの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

例がうまくいかないのは、バックグラウンドコマンドがサブシェル環境で実行され、値が$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

おすすめ記事