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:
ls -R 2>&1 > a
- File a contains itself and doesn't contain the error msg - WHY?ls -R 2>&1- > a
- nothing changes from the situation above - SO WHAT'S THE POINT IN MOVING FDls -R 1>&2 > a
- still nothing changesls -R 1>&2- > a
- no error msg displayed and error msg still not visible in the filels -R > a 2>&1
- both streams are redirected to file - works as expectedls -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:
- What is the difference between redirecting output
[n]>word
and duplicating fd[n]>&digit
and which one is used the I do2>&1
- Why in case
1
and2
the output file doesn't contain the error message - the stderr stream has been redirected to the stdout - What's the use case of Moving FD?
- 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