3

I am trying to understand the Bash redirections (3.6. Redirections). I prepared the test envronment and I'm trying to understand the order of operations with redirections and order of created file descriptors.

Test env preparation:

cd `mktemp -d`
mkdir no_access_dir
chmod 000 no_access_dir

ls -R outpus is the following:

.:
no_access_dir
ls: cannot open directory './no_access_dir': Permission denied

First 2 stdout lines followed by 1 stderr output.

I checked the behavior of commands using the 3.6.2 Redirecting Output, 3.6.4 Redirecting Standard Output and Standard Error, 3.6.8 Duplicating File Desciptors and 3.6.9 Moving File Desciptors

Here are the test commands :

ls -R 2>&1 > a    # 1. 3.6.2 or 3.6.8
ls -R 2>&1- > a   # 2. 3.6.9
ls -R 1>&2 > a    # 3. 3.6.2 or 3.6.8
ls -R 1>&2- > a   # 4. 3.6.9
ls -R > a 2>&1    # 5. 3.6.4
ls -R > a 1>&2    # 6. 3.6.4

Output descriptions:

  1. ls -R 2>&1 > a - File a contains itself and doesn't contain the error msg - WHY?
  2. ls -R 2>&1- > a - nothing changes from the situation above - SO WHAT'S THE POINT IN MOVING FD
  3. ls -R 1>&2 > a - still nothing changes
  4. ls -R 1>&2- > a - no error msg displayed and error msg still not visible in the file
  5. ls -R > a 2>&1 - both streams are redirected to file - works as expected
  6. ls -R > a 1>&2 - File a is empty because stdout is redirected to stdout

I understand the output in 5 and 6, however why in commands 1, 2, 3 the output is the same - and why number 4 doesn't display the error message nor this message is saved in a file - it's a mystery.

So my questions are:

  1. What is the difference between redirecting output [n]>word and duplicating fd [n]>&digit and which one is used the I do 2>&1
  2. Why in case 1 and 2 the output file doesn't contain the error message - the stderr stream has been redirected to the stdout
  3. What's the use case of Moving FD?
  4. Where is the error message from 4? It's not in the output file and it's not in the console.

My current understanding is: ls -R > a 2>&1 - first Bash creates file a then runs a command ls -R which finds the newly created file a and displays the stderr msg which is redirected to stdout and saved to file - but the syntax in this case is very ambiguous

1

1 Answer 1

0

The issue is kind of in the timing - the position on the command line matters, since the redirections are applied in sequence as they are encountered. So for points 1-4, it doesn't matter that there is a > a coming afterwards - that will only be applied when it is eventually reached. Everything done to &2 happens before the > a, so redirecting to &1 at that point will still refer to what it was before, i.e. your terminal output

You must log in to answer this question.

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