Why isn’t my shell script redirect working?

Sometimes we want to pipe a script’s output into grep or less. This is pretty straight forward:

$ my-script.sh | less

But sometimes it just won’t work. That’s when we learn the 2>&1 idiom. The previous example turns into:

$ my-script.sh 2>&1 | less

If we want to have that output go to a file, we then substitute “| less” for “>my-script.log”. Fair and square:

$ my-script.sh 2>&1 >my-script.log

output

more output

Wait! That’s not what I wanted!

If you look closely you’ll noticed that the stdout redirect appears before the stderr one. But since Bash processes redirects sequentially, when it redirects stderr to stdout, stdout is still the original output, which is probably the console.

What you want to do is swap the redirects like so:

$ my-script.sh >my-script.log 2>&1

$

With that, both stdout and stderr will be redirected to the my-script.log file.

For more information, plese take a look at this link.

https://www.gnu.org/software/bash/manual/html_node/Redirections.html

Until next time!

Leave a comment