1

This is my test .sh file.

errorandoutput.sh

#!/bin/bash

echo myecho
ls dflj

If I run ./errorandoutput.sh >file 2>&1,then we can get such file

But I hope the STDOUT information is after the STDERR.So I change the command into

./errorandoutput.sh >file 1>&2

But I get a empty file.How to make the the STDOUT information is after the STDERR in a redirect file?


I mean I hope I can get a file like

ls: cannot access 'dflj': No such file or directory
myecho

3 Answers 3

2

That's not how order of redirection work.

The order of redirection only determine the order of action the shell does with file description, not its content.

In:

./errorandoutput.sh >file 2>&1

First, the shell redirect standard out to file, then redirect standard error to standard out, which is now pointed to file, so both standard out and standard error now go to file.

At this stage, the shell is done with redirection. It has nothing to do with content of file file.

The order of content in file is determine by the order of commands you ran inside script. Change your script to:

#!/bin/bash

ls dflj
echo myecho

and you would got what you want.

0

the '>' acts like "1**>**"

this way it should work

./errorandoutput.sh  2>file  1>&2



$ ( echo yay ; fhgfhgf ) > out 2>&1
$ cat out
yay
bash: fhgfhgf: command not found
$ ( echo yay ; fhgfhgf ) 2> out 1>&2
$ cat out
yay
bash: fhgfhgf: command not found
2
  • But I get a same file
    – yode
    Commented Jul 10, 2017 at 2:51
  • sorry i misunderstand , i saw the 'But I get a empty file' , i thought you wanna inverse FDs order,
    – Yunus
    Commented Jul 10, 2017 at 3:51
0

If it's important, send the standard output to a file and then output it afterwards. This would of course require a script:

temp=/tmp/yc$$
yourcommand > ${temp}
cat ${temp} && rm -f ${temp}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .