我正在开发这个脚本:
#!/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中将来自多个子进程的流收集到一个输出中?
答案 0 :(得分:0)
尝试以下方法:
# ...
rm -f fifo
mkfifo fifo
for f in $*; do
tail -f "$f" | awk '{ print "'"$f"':"$0 }' > fifo &
done
tail -f fifo
# ...
答案 1 :(得分:0)
您可能只需要将循环更改为:
for f; do
tail -f "$f" | awk -v f="$f" '{ printf "%s : %s\n", f, $0 }' &
done
使用$ *会使其受到分词的影响。