I have a bash script with many commands, some of which might generate error messages. often, the error messages and output messages are mixed in an apparently incorrect order (for example, I see the output of command #2 and then an error message from command #1).

As far as I understand, the reason is that the commands use two output streams - stdout and stderr - and each of them is printed to the console asynchronously. So, one solution is to redirect stderr to stdout by adding "2>&1" after each command.

But since I have many commands, it would be better to do this once for all commands. Is there a single command that I can put at the start of the script, that will ensure that all error messages from all commands are redirected to stdout, so that all output appears in the correct order?

  • Is the inter-mingling of output due to running concurrent jobs in the script? In that case, merging of the streams may not be the solution. – Kusalananda Mar 11 '19 at 8:11
  • @Kusalananda No, there are no concurrent jobs. – Erel Segal-Halevi Mar 11 '19 at 8:14
  • In that case, could you share a small example code that shows (reproduces) this inter-mingling? I can't see how errors from one command would show up after the output from another command that executes later. – Kusalananda Mar 11 '19 at 8:16
  • Yes. exec 2>&1 – Uncle Billy Mar 11 '19 at 8:26

Although I don't quite see how the standard output and error streams would get mixed up in each other between two or more non-concurrent commands, you could make the script redirect two output streams to the same place with a single command at the start of the script:

exec 2>&1

Or, you could start the script with a redirection:

./myscript.sh 2>&1

Personally, I would go for the second of these options as it would allow you to more easily turn this "feature" on or off.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.