[Unix] pipe error to less, grep, tail
默认是bash
To pipe only the error output (stderr) of a command to tail on a Unix system, use this syntax:
command 2>&1 >/dev/null | tail
Explanation:
-
commandis any Unix command. -
2>&1redirects stderr (file descriptor 2) to stdout (file descriptor 1). -
>/dev/nulldiscards the original stdout, so only stderr is left. -
The result is that only stderr is passed to
tail.
Example:
ls /nonexistent 2>&1 >/dev/null | tail
This will show only the error message from ls (since /nonexistent does not exist) and pipe it through tail.
If you want to see both stdout and stderr, just do:
command 2>&1 | tail
Want to pipe stderr and stdout separately or to different places?
If you want to pipe stdout and stderr separately (e.g., to different commands or files), here are several canonical idioms in Unix shell (assuming bash or similar Bourne-style shell):
1. Send stdout to one command, stderr to another
You can use process substitution:
command > >(stdout_handler) 2> >(stderr_handler)
Example:
make > >(tee stdout.log) 2> >(tee stderr.log >&2)
-
makeruns -
stdoutgoes totee, which saves tostdout.log -
stderrgoes to anothertee, which saves tostderr.log -
>&2sendstee's output back to stderr so it behaves correctly
2. Pipe only stderr to tail and discard stdout
command 2>&1 1>/dev/null | tail
As discussed previously.
3. Pipe stdout to tail, discard stderr
command 2>/dev/null | tail
4. Send stderr to a file, stdout to another
command > out.log 2> err.log
5. Interleave both stdout and stderr, and pipe them together
command 2>&1 | tee combined.log | tail
Unix shell redirection is exacting and low-level; once you learn the logic of file descriptors (0: stdin, 1: stdout, 2: stderr), you can route anything anywhere. Need an example with grep, awk, or curl?
例如:
ffprobe abc.mp3 2>&1 1>/dev/null | tail -4

浙公网安备 33010602011771号