1

我正在开发这个脚本:

#!/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 中是否可以将来自多个子进程的流收集到一个输出中?

4

2 回答 2

0

尝试以下操作:

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

tail -f fifo
# ...
于 2013-08-30T15:12:45.620 回答
0

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

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

使用 $* 会使它受到分词的影响。

于 2013-08-30T15:47:36.347 回答