In Linux/Unix, everything is a file. Regular file, Directories, and even Devices are files.
Every File has an associated number called File Descriptor (FD).
Whenever you execute a program/command at the terminal, 3 files are always open, viz., standard input, standard output, standard error.
These files are always present whenever a program is run.
File | File Descriptor |
---|---|
Standard Input STDIN | 0 |
Standard Output STDOUT | 1 |
Standard Error STDERR | 2 |
The keyboard is the standard input device while your screen is the standard output device.
However, files can have their input and output redirected, using:
The '>' symbol is used for output (STDOUT) redirection.
ls -al > listings
Here the output of command ls -al is re-directed to file “listings” instead of your screen.
NOTE: Use the correct file name while redirecting command output to a file.
If there is an existing file with the same name, the redirected command will delete the contents of that file and then it may be overwritten.
If you do not want a file to be overwritten but want to add more content to an existing file, then you should use '»' operator.
You can redirect standard output, to not just files, but also devices!
cat music.mp3 > /dev/audio
The cat command reads the file music.mp3 and sends the output to /dev/audio which is the audio device.
If the sound configurations in your PC are correct, this command will play the file music.mp3.
The '<' symbol is used for input (STDIN) redirection.
Mail -s "Subject" to-address < Filename
This would attach the file with the email, and it would be sent to the recipient.
Error re-direction is one of the very popular features of Unix/Linux.
Frequent UNIX users will reckon that many commands give you massive amounts of errors.
The solution is to re-direct the error messages to a file.
myprogram 2>errorsfile
Executes a program names myprogram.
The file descriptor for standard error is 2.
Using “2>” we re-direct the error output to a file named “errorfile”
Thus, program output is not cluttered with errors.
find . -name 'my*' 2>error.log
Using the “find” command, we are searching the “.” current directory for a file with “name” starting with “my”.
A more complex example,
Server Administrators frequently, list directories and store both error and standard output into a file, which can be processed later.
ls Documents ABC> dirlist 2>&1
Here,