I tried to swap stdout and stderr and redirect each stream to the files, in bash interactive shell.

By using brace Grouping command, I gained the output what I want. But I do not understand why when I do not use Grouping command, the result is not be swapped.

$ # Using Grouping command. Swap operation is succeed.
$ { { echo stdout; echo stderr 1>&2; } 3>&1 1>&2 2>&3; } 1>1.txt 2>2.txt;
$ cat 1.txt
$ cat 2.txt

$ # Not using Grouping command. Swap is failed...
$ { echo stdout; echo stderr 1>&2; } 3>&1 1>&2 2>&3 1>1.txt 2>2.txt;
$ cat 1.txt
$ cat 2.txt

My understanding of the operation of swapping file descriptors with respect to the above command was as follows.

  1. 3>&1: redirect FD3 to FD1 (stdout)
  2. 1>&2: redirect FD1 to FD2 (stderr)
  3. 2>&3: redirect FD2 to FD3 (stdout)
  4. 1>1.txt: redirect FD1 to 1.txt (FD1 points to stderr)
  5. 2>2.txt: redirect FD2 to 2.txt (FD2 points to stdout)

But under my understanding, I think the result should not change depending on whether there are braces or not.

Am I making some basic misunderstandings? Why do the above two command results differ?

Info my env.

$ bash --version
GNU bash, version 4.4.12(1)-release (x86_64-apple-darwin16.3.0)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

1 Answer 1


Bash processes file descriptors in reverse order, so from right to left. First 2>2.txt, then 1>1.txt, and so on...

  • Are there any reference pages? I think this processing order is left to right. reference: Bash Reference Manual 3.6 Redirections > The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right.
    – fhiyo
    Oct 27, 2017 at 1:08

You must log in to answer this question.

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