Redirecting redirections

We already gave you a sneak preview of the process of redirecting redirections. The most famous example, which was mostly used before Bash 4.x, is redirecting the stderr stream to the stdout stream. By doing this, you can redirect all output with just the > syntax.

You can achieve it like this:

reader@ubuntu:/tmp$ cat /etc/shadow
cat: /etc/shadow: Permission denied
reader@ubuntu:/tmp$ cat /etc/shadow > shadow
cat: /etc/shadow: Permission denied
reader@ubuntu:/tmp$ cat shadow
#Still empty, since stderr wasn't redirected to the file.
reader@ubuntu:/tmp$ cat /etc/shadow > shadow 2>&1
#Redirect fd2 to fd1 (stderr to stdout).

reader@ubuntu:/tmp$ cat shadow
cat: /etc/shadow: Permission denied

Remember, you no longer need this syntax with Bash 4.x, but if you ever want to use your own custom file descriptors as input/output streams, this will be useful knowledge. By ending the command with 2>&1, we're writing all stderr output (2>) to the stdout descriptor (&1).

We can also do it the other way around:

reader@ubuntu:/tmp$ head -1 /etc/passwd
root:x:0:0:root:/root:/bin/bash
reader@ubuntu:/tmp$ head -1 /etc/passwd 2> passwd
root:x:0:0:root:/root:/bin/bash
reader@ubuntu:/tmp$ cat passwd
#Still empty, since stdout wasn't redirected to the file.
reader@ubuntu:/tmp$ head -1 /etc/passwd 2> passwd 1>&2
#Redirect fd1 to fd2 (stdout to stderr).
reader@ubuntu:/tmp$ cat passwd
root:x:0:0:root:/root:/bin/bash

So now, we're redirecting the stderr stream to the passwd file. However, the head -1 /etc/passwd command only delivers an stdout stream; we're seeing it printed to the Terminal instead of to the file.

When we use 1>&2 (which could also be written as >&2) we're redirecting stdout to stderr. Now it is written to the file and we can cat it there!

Remember, this is advanced information, which is mostly useful for your theoretical understanding and when you start working with your own custom file descriptors. For all other output redirections, play it safe and use the &> syntax as we discussed earlier.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.127.57