How to Use Redirection at the Command Line, a Basic Overview
Ever wished you could send the output of a command to a file or append that output to an existing file? That’s what redirects do. To put it simply, command line redirects allow you to take the output of certain commands and create new files or add to existing ones with this data, this is incredibly useful indeed, and the knowledge expands to OS X, Linux, and any other variant of Unix.
In our continued quest to propagate OS X command line knowledge, we bring you some information on the extremely useful redirect utilities.
Redirect the Output of a Command to a New File
The most basic usage of a redirect is as follows:
command > newfile
This will take the output of ‘command’ and place it into a file called ‘newfile’, for example:
ls -la > directorylisting.txt
That would place the output of ls -la into a file called directorylisting.txt. Easy!
Appends the Output of a Command to the End of Existing File (EOF)
If you have an existing file you wish to append the output of a command to, simply use this form of redirect:
command >> existingfile
Examples of Command Line Redirects in Use
If you wanted to create a text file with data from the ps command, but controlled only for Dashboard related processes running, this is what you would type at the command line:
ps -aux | grep Dashboard > dashboarddata.txt
If you wanted to add at the end of the file we just created, dashboarddata.txt a list of Widgets you have installed, you would type the following:
ls -l /Library/Widgets >> dashboarddata.txt
The uses for redirection are endless and you’ll find that the more time you spend in the command line, the more you’ll want to use redirect for aiding certain tasks.
Mac OS X is so user friendly that many Mac users probably don’t know they’re sitting on top of a powerful Unix base, accessible by the Terminal app. Our feeling is that since the command line is there, you should be able to use it to some extent. So read on, or explore our Command Line articles for much more.