questions about bash redirects

Hello! Here are some questions & answers. The goal isn't to get all the questions "right". Instead, the goal is to learn something! If you find a topic you're interested in learning more about, I'd encourage you to look it up and learn more.

by default, a Unix program has 3 inputs / outputs. What are they?

  1. stdin (for input, like from a pipe)
  2. stdout (for regular output)
  3. stderr (an output for debugging information, errors, and any informational messages meant for a human to read)

when you run a program from a terminal, where does stdout output to?

the terminal!

stdin, stderr, and stdout all use the terminal by default

how do you redirect a program's output to a file?

$ some_cmd > file.txt

how do you redirect a program's error output to a file?

$ some_cmd 2> file.txt

how do you set a program's input (stdin) to be a file instead of the terminal?

$ some_cmd < file.txt

what's a way to ignore a program's output?

$ some_cmd > /dev/null

/dev/null is a special file. The operating system completely ignores all writes to /dev/null.

why is the number 2 in
$ ls 2> file.txt
2 and not 4 or 7 or 13?

it's the file descriptor number!

every Unix program has a number called a "file descriptor", and the first 3 numbers are generally reserved for stdin/stdout/stderr:

  • 0 for stdin
  • 1 for stdout
  • 2 for stderr

how do you redirect stderr output to stdout?

$ some_cmd 2>&1

I often end up running something like

$ strace ls 2>&1 | grep whatever

when I want to grep error output

which one is the right syntax for redirecting both stdout and stderr to a file?

$ some_cmd 2>&1 > file
$ some_cmd > file 2>&1

$ some_cmd > file 2>&1

This one always looks weird to me, but it's the only one that works.

will sudo echo x > /file allow you to redirect to /file if it's owned by root?

nope!

It doesn't work because bash opens /file to manage the redirect before echo starts, and bash is running as you.

This works, though:

echo x | sudo tee /file

tee copies everything from its standard input to stdout and a file. Because tee is responsible for opening the file (and not bash), sudo tee will be able open /file as root

more reading