Unit 3 路 Linux^2 路 Lesson 24 of 34
Redirect Me
Where'd my output go?
Up until now, everything you've run just spits its output onto your screen and that's it. Sometimes you actually want to keep that output though, like saving the results of a grep so you don't have to run it all over again. That's where redirection comes in.
Saving output with >
The > symbol takes the output of a command and shoves it into a file instead of showing it on your screen.
[user@linux]$ echo hello > greeting.txt
If greeting.txt doesn't exist yet, Linux makes it for you. If it already does exist... it gets completely overwritten. No warning, no "are you sure?", just gone.
鈿狅笍 Remember: Linux won't question you!
Adding to a file with >>
If you want to add onto the end of a file instead of replacing it, use >> instead.
[user@linux]$ echo "another line" >> greeting.txt
Sending errors away with 2>
You can also send errors somewhere else using 2>. This is super handy when a command spams Permission denied all over your screen and you only want the actual results.
[user@linux]$ grep -r "flag" / 2> /dev/null
/dev/null is basically the black hole of Linux. Anything you send there is gone forever, which is exactly what we want for those annoying errors.
You can use > and 2> in the same command too. The output goes one way, the errors go the other:
[user@linux]$ grep -r "flag" / > results.txt 2> /dev/null
Passing output along with |
> sends output into a file, but what if you want to send it into another command instead? That's what the pipe (|) is for. It takes whatever the first command spits out and hands it to the next one.
[user@linux]$ ls /etc | grep pass
ls lists everything in /etc, and instead of dumping all of it on your screen, grep only shows you the lines with "pass" in them. You can chain as many pipes together as you want, and you'll be doing it constantly from here on out.
Two commands that go great with pipes are head and tail, which show just the first or last few lines of something:
[user@linux]$ ls /etc | head -5
[user@linux]$ ls /etc | tail -1
(Leave off the number and you get 10 lines.)
Quick recap
Try it
There's a program called noisy in ~/redirect. It knows a secret, but it's the worst: it buries your screen in Permission denied errors, and it refuses to say the secret to your face. Run it once (./noisy) just to see how bad it is, then tame it with what you just learned.
馃挕
noisyactually tells you what it wants if you read what it says. Errors in Linux are usually trying to help!
Live Linux terminal
This lesson comes with a real Ubuntu machine that runs in your browser, so you type every command yourself. Create a free account to do this part.
Do this lesson for real
With a free account you get the terminal, the challenges and the checks that go with every lesson in Intro to Linux, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.