redirect - The order of stdout and stderr in bash -
ls test.mp4 test.sh 1>/tmp/text 2>&1 cat /tmp/text ls: cannot access test.sh: no such file or directory test.mp4
why result not following order?
test.mp4 ls: cannot access test.sh: no such file or directory
maybe 1>/tmp/text
executed first, , test.mp4 locate before test.sh.
result in effect?
this has nothing bash. reflects way c standard library i/o functions buffer output.
here's useful excerpt man setvbuf
on linux system (the explanation derived c , posix standards, think it's easy find , understand in excerpt). second paragraph explanation behaviour see.
the 3 types of buffering available unbuffered, block buffered, , line buffered. when output stream unbuffered, information appears on destination file or terminal written; when block buffered many characters saved , written block; when line buffered characters saved until newline output or input read stream attached terminal device (typically stdin). function fflush(3) may used force block out early. (see fclose(3).)
normally files block buffered. if stream refers terminal (as stdout does), line buffered. standard error stream stderr unbuffered default.
so, recap. stdout
refers terminal , therefore line-buffered, have redirected file block buffered. however, stderr
unbuffered whether or not has been redirected.
consequently, printed stderr
appears immediately, while printed stdout
held until buffer fills (on linux, 8kb).
note when ls
detects stdout
not terminal, sets -1
flag default (one filename per line). otherwise, set -x
flag default (as many filenames fit on line). means see same inversion on terminal without redirecting @ all:
$ ls bad ls: cannot access bad: no such file or directory
Comments
Post a Comment