bash异步函数

时间:2011-01-17 16:40:54

标签: bash

我有一个for循环,在循环中,有while循环,问题是当while循环执行时,下一个for循环从未执行。

sync[0]='/home/lzyy/tmp,12.34.56.78,test'
sync[1]='/home/lzyy/tmp,23.45.67.89,test'

for item in ${sync[@]}; do

echo $item #only output sync[0]
dir=`echo $item | awk -F"," '{print $1}'`
host=`echo $item | awk -F"," '{print $2}'`
module=`echo $item | awk -F"," '{print $3}'`

inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format  '%T %w%f %e' \
 --event CLOSE_WRITE,create,move,delete  $dir | while read  date time file event
    do
        echo 
        # do something, 
    done
done

我能找到解决这个问题的方法是异步函数,或者将while循环保存在一个单独的文件中,并执行后台。

1 个答案:

答案 0 :(得分:4)

您的inotifywait ... | while read ...; do ... done实际上是bash中的单个命令(单个管道),因此您可以在其后安全地添加&以使其在后台运行。基本上,它看起来像这样:


inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format  '%T %w%f %e' \
 --event CLOSE_WRITE,create,move,delete  $dir | while read  date time file event
    do
        echo 
        # do something, 
    done &