重定向bash脚本中多个子进程的输出



我正在开发这个脚本:

#!/bin/bash
# If no command line arguments, display a tiny usage message.
if [[ $# -eq 0 ]]; then
  echo "Usage: $0 files..." >&2
  exit 1
fi
# Destroy child processes, when exiting.
cleanup() {
  kill `jobs -p` 2>/dev/null
}
# Call cleanup function on SIGINT, ie. Ctrl-C.
trap "cleanup; exit 0" INT TERM EXIT
# Start child processes continously outputting from the files given as command
# line arguments. The filename is prepended on the line.
for f in $*; do
  tail -f "$f" | awk '{ print "'"$f"':"$0 }' &
done
# Wait for child processes to exit. Just to be sure, kill them all afterwards.
wait
cleanup

我是这样使用的:

tailfiles *.log

它所做的是交错所有文件的尾部输出,并以文件名为前缀(有点像grep -H)。但是,我无法通过管道传输脚本的输出。它很简单,什么也没给我:

tailfiles *.log | grep error

在bash中,是否可以将来自多个子进程的流收集到一个输出中?

尝试以下操作:

# ...
rm -f fifo
mkfifo fifo
for f in $*; do
  tail -f "$f" | awk '{ print "'"$f"':"$0 }'  > fifo  &
done
tail -f fifo
# ...

您可能只需要将循环更改为:

for f; do
  tail -f "$f" | awk -v f="$f" '{ printf "%s : %sn", f, $0 }' &
done

使用$*会使其受到分词处理。

相关内容

  • 没有找到相关文章

最新更新