当另一个进程没有输出时重复执行 bash 命令

当另一个进程没有输出时重复执行 bash 命令

我在跑fs_usage检测对我的文件系统上的对象的访问。

sudo fs_usage -w | grep -E 'object'

touch现在,只要上述命令在 5 秒内没有新输出,我想每 5 秒对该对象运行一次命令。

答案1

sudo fs_usage -w | while true; do
    if read -rt5 && [[ $REPLY =~ objectpattern ]]; then
        # Some output happened in the last 5 seconds that matches object pattern
        :
    else 
        touch objectfile
    fi
done

当然,使用read -t意味着有可能有一些输出不是匹配objectpattern;如果发生这种情况,该文件将被触及。如果你想避免这种情况,我们就必须变得更复杂一些。

timeout=5
sudo fs_usage -w | while true; do
    (( mark = SECONDS + timeout ))
    if !read -rt$timeout; then
        touch objectfile
        timeout=5
    elif ![[ $REPLY =~ objectpattern ]]; then
        # Some output happened within timeout seconds that does _not_ match.
        # Reduce timeout by the elapsed time.
        (( timeout = mark - SECONDS ))
        if (( timeout < 1 )); then
            touch objectfile
            timeout=5
        fi
    else
        timeout=5
    fi
done

答案2

如果我理解正确的话,那么你可能想做:

sh -c '{ fsusage             #your command runs (indefintely?)
         kill -PIPE "$$"     #but when it completes, so does this shell
       } >&3 &               #backgrounded and all stdout writes to pipe
       while sleep 5         #meanwhile, every 5 seconds a loop prints
       do    echo            #a blank line w/ echo
       done' 3>&1 |          #also to a pipe, read by an unbuffered (GNU) sed
sed -u '
### if first input line, insert shell init to stdout
### for seds [aic] commands continue newlines w/ \escapes
### and otherwise \escape only all other backslashes
1i\
convenience_func(){ : this is a function  \\\
                      declared in target  \\\
                      shell and can be    \\\
                      called from sed.; }
### if line matches object change it to command
/object/c\
# this is an actual command sent to a shell for each match
### this is just a comment - note the \escaped newlines above                    
### delete all other nonblank lines; change all blanks
/./d;c\
# this is a command sent to a shell every ~5 seconds
' | sh -s -- This is the target shell and these are its   \
             positional parameters. These can be referred \
             to in sed\'s output like '"$1"' or '"$@"' as \
             an array. They can even be passed along to   \
             'convenience_func()' as arguments.

上面大约90%都是评论。基本上可以归结为...

sh -c '(fsusage;kill "$$") >&3 &
       while sleep 5; do echo; done
' 3>&1| 
sed -nue '/pattern/c\' -e 'echo match
          /./!c\'      -e 'touch -- "$1"
' | sh -s -- filename

相关内容