{
echo bla1
echo bla2 1>&2
} >>myfile 2>&1
Is there any difference between the two echo
-s?
The only difference I can think of, if echo bla2 2>&1
retains the unbuffered property from stderr.
How about
{
echo bla1
echo bla2 1>&2 &
} >>myfile 2>&1
?
Is it the same as
{
echo bla1
echo bla2 &
} >>myfile 2>&1
?
After {...} >>myfile 2>&1
will fd1 and fd2 essentially become the same thing, or do they retain anything from their past?
EDIT:
Building on the answer from @ilkkachu, I tried the following:
perl -e 'print "foo"; sleep 2; print "bar\n"; sleep 2; print "bla"'
# ^^^line buffered
perl -e 'print "foo"; sleep 2; print "bar\n"; sleep 2; print "bla"' | cat
# ^^^block buffered
touch myfile; tail -f myfile &
perl -e 'print "foo"; sleep 2; print "bar\n"; sleep 2; print "bla"' >>myfile 2>&1
# ^^^block buffered
perl -e 'print STDERR "foo"; sleep 2; print STDERR "bar\n"; sleep 2; print STDERR "bla"'
# ^^^unbuffered
perl -e 'print STDERR "foo"; sleep 2; print STDERR "bar\n"; sleep 2; print STDERR "bla"' 2>&1 | cat
# ^^^unbuffered
perl -e 'print STDERR "foo"; sleep 2; print STDERR "bar\n"; sleep 2; print STDERR "bla"' >>myfile 2>&1
# ^^^unbuffered
In case of fd1, the buffering is adjusted according to the output type.
In case of fd2, the output was irrelevant.
{ echo -n foo; sleep 2; echo bar; sleep 2; echo -n bla; }
# ^^^unbuffered
{ echo -n foo; sleep 2; echo bar; sleep 2; echo -n bla; } | cat
# ^^^unbuffered
touch myfile; tail -f myfile &
{ echo -n foo; sleep 2; echo bar; sleep 2; echo -n bla; } >>myfile 2>&1
# ^^^unbuffered
{ echo -n foo 1>&2; sleep 2; echo bar 1>&2; sleep 2; echo -n bla 1>&2; }
# ^^^unbuffered
{ echo -n foo 1>&2; sleep 2; echo bar 1>&2; sleep 2; echo -n bla 1>&2; } | cat
# ^^^unbuffered
{ echo -n foo 1>&2; sleep 2; echo bar 1>&2; sleep 2; echo -n bla 1>&2; } >>myfile 2>&1
# ^^^unbuffered
It seems, echo
always flushes, regardless where the output is going.
The experiment was repeated with
{ printf foo; sleep 2; printf 'bar\n'; sleep 2; printf bla; }
as well, the results were identical to echo
.
Result: In the above cases, the buffering was determined by the writer.
echo
as some program writing in stderr and stdout. – Zoltan K. Sep 15 '21 at 17:03echo
, corrected to1>&2
. – Zoltan K. Sep 15 '21 at 22:32