stdin, stderr, and stdout all use the terminal by default
$ some_cmd > file.txt
$ some_cmd 2> file.txt
$ some_cmd < file.txt
$ some_cmd > /dev/null
/dev/null
is a special file. The operating system
completely ignores all writes to /dev/null
.
2
in $ ls 2> file.txt
every Unix program has a number called a "file descriptor", and the first 3 numbers are generally reserved for stdin/stdout/stderr:
$ some_cmd 2>&1
I often end up running something like
$ strace ls 2>&1 | grep whatever
when I want to grep error output
$ 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.
sudo echo x > /file
allow you to redirect to
/file
if it's owned by root?
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