Today, we’re going to talk about Bash and input/output redirection. This is pretty standard stuff for any Unix and Linux user, but there are a few ins and outs that nobody ever told me about. Let’s just use some examples:
Pretty standard stuff, write all standard output to a file:
# write the stdout of mycommand to myfile.log
mycommand > myfile.log
Write all standard output and standard error to a file:
# write the stdout and stderr of mycommand to myfile.log
mycommand 2>&1 > myfile.log
Write standard input to one file and standard error to another file:
# write stdout of mycommand to myfile.log and stderr of mycommand to myfile.error.log
mycommand 2> myfile.error.log > myfile.log
Append standard output to a file (not completely overwriting it as above):
# append stdout of mycommand to myfile.log
mycommand >> myfile.log
The same can be done with stderr:
# append stderr of mycommand to myfile.error.log
mycommand 2>> myfile.error.log
You can also force-clobber the file if you really want it to overwrite things:
# force-overwrite stdout of mycommand to myfile.log
mycommand >! myfile.log
Now, let’s move on to piping.
Instead of writing all standard output to a file, we’ll print it and write it to a file with tee:
# pipe the stdout of mycommand to `tee`, which will print it and write it to myfile.log
mycommand | tee myfile.log
What about standard error, though? You can redirect standard error to standard out:
# pipe the stdout of mycommand (pushing stderror to stdout) to `tee`
mycommand 2>&1 | tee myfile.log
Or, redux: accomplish that whole standard error redirect in less characters:
mycommand |& tee myfile.log
And, just for kicks, redirect standard output to standard error:
mycommand >&2
As far as Bash i/o redirection goes, that’s pretty much it. Have fun!
Filed under: Bash, bash, io |