This week, we're learning about I/O Redirection. I/O stands for input/output and it lets you redirect the input and output of commands to and from files, and connect multiple command "pipelines". I'm also going to introduce some new commands we haven't covered yet in the next coming weeks. Let's get started!
First we need to understand that all programs in the terminal give you some sort of output, whether that's a result or a status/ error message. These outputs send results over to a file called standard output (stdout) and messages to a file called standard error (stderr). By default, these files aren't saved to the disk. Also, the keyboard is automatically tied to the standard input (stdin) facility. So now, we have I/O redirection to change where the output goes (instead of just the screen) and where input comes from (instead of just the keyboard).
Let's test this. We're going to change the standard output result to save to a text file. Type ls -l /usr/bin > ls-output.txt. This gives you a long listing of /usr/bin and sends results to that text file. If you check it with ls -l ls-output.txt, the text file has been saved. View it with less by typing less ls-output.txt.
Let's try to redirect an output for a directory that doesn't exist. ls -l /bin/usr > ls-output.txt. Obviously, there's an error message because /bin/usr doesn't exist (but usr/bin does.). It's not redirected to the new .txt file because we haven't told ls to redirect error files, just resulting standard outputs. Now check out the old txt file. ls -l ls-output.txt. It has no length because the redirection operator (>) always rewrites from the beginning. The redirection operator started writing a new file, but stopped when it got this error and instead just sent the error to the screen for all to see.
Shortcut! If you ever want to quickly create a new file use > yourfile.txt. To append the output file instead of overwriting it, use the >> operator instead of just one >. ls -l /usr/bin >> ls-output.txt. Now, the txt file will be created and saved to. So, if you type this same command in three, four, five times, it'll keep saving to it instead of overwriting each time! ls -l /usr/bin >> ls-output.txt x3 then ls -l ls-output.txt to check it. You'll be able to see that the file keeps growing in size.
Next week, I'll be covering how to redirect those standard errors, but first make sure to email me firstname.lastname@example.org with your thoughts, or comment below. And be sure to check out our sister show, Hak5 for more great stuff just like this. I'll be there, reminding you to trust your technolust.