简体   繁体   中英

tail -f file1 | perl -pe '$_' > file2 does not output anything to file2

This command does not output anything to file2:

#!/bin/bash
echo content > file1
tail -f file1 | perl -pe '$_' > file2

Whereas these commands work ok:

tail -f file1 > file2
tail -f file1 | perl -pe '$_'
tail file1 | perl -pe '$_' > file2
tail -f /tmp/file1 | while read line; do echo $line | perl -pe '$_' > /tmp/file2 ; done

Anyone knows what's happening?

perl has detected that stdout is not a terminal. For efficiency, it waits until it has a full block of data to write. Since you don't provide more data, it won't write anything until tail exits and the program can finish.

You can enable autoflushing with $|++ :

tail -f file1 | perl -pe '$|++; $_' > file2

The one with no output suffers from a combination of buffered output and non-termination. tail -f will never exit, waiting forever for file1 to grow. However, the output of perl is (apparently) buffered, so it waits until it has some minimal amount of output (more than a single line containing "content") to actually write to file2 . Until more output is generated, or perl exits, the output remains unflushed.

Each of your working examples either terminates, flushing any buffered output at that time; or its output is unbuffered, allowing it to appear as it is generated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM