Quando você deseja redirecionar stdout e stderr para o mesmo arquivo, pode fazê-lo usando command 1>file.txt 2>&1
, ou command &>file.txt
. Mas por que o comportamento é command 1>file.txt 2>file.txt
diferente dos dois comandos acima?
A seguir, é um comando de verificação.
$ cat redirect.sh
#!/bin/bash
{ echo -e "output\noutput" && echo -e "error" 1>&2; } 1>file.txt 2>&1
{ echo -e "output\noutput" && echo -e "error" 1>&2; } 1>file1.txt 2>file1.txt
{ echo -e "error" 1>&2 && echo -e "output\noutput"; } 1>file2.txt 2>file2.txt
{ echo -e "output" && echo -e "error\nerror" 1>&2; } 1>file3.txt 2>file3.txt
{ echo -e "error\nerror" 1>&2 && echo -e "output"; } 1>file4.txt 2>file4.txt
$ ./redirect.sh
$ echo "---file.txt---"; cat file.txt;\
echo "---file1.txt---"; cat file1.txt; \
echo "---file2.txt---"; cat file2.txt; \
echo "---file3.txt---"; cat file3.txt; \
echo "---file4.txt----"; cat file4.txt;
---file.txt---
output
output
error
---file1.txt---
error
output
---file2.txt---
output
output
---file3.txt---
error
error
---file4.txt----
output
rror
Tanto quanto os resultados são vistos, parece que a segunda string de eco substitui a primeira quando você executa command 1>file.txt 2>file.txt
, mas não sei por que. (Existe uma referência em algum lugar?)