Hello Linux-fanatics, in our previous tutorials we have discussed how we can redirect output of a script to a file or use a file as input in our scripts. We will now discuss I/O redirection in little more depth.
As we know Linux treated every object as files & every file is identified as a file descriptor with each process having upto 0 file descriptors. BASH reserves 3 of total 9 file descriptors. List of these reserved descriptors is as follow
File Descriptor Number Purpose
- 0 STDIN (Standard Input)
- 1 STOUT (Standard output)
- 2 STDERR (Standard Error)
STDIN refers to standard Input for the shell, which by default is the keyboard. But we can a file as standard input using “>” symbol.
STDOUT refers to standard output for the shell, which is monitor by default. But we can redirect output to a file with “<” symbol.
STDERR refers to standard error output to the shell, which is monitor by default. But are also redirected to a file when we redirect STOUT to a file.
Now, we will learn to redirect STDERR/errors to a file without redirecting STDOUT/output of a script or redirecting both STDERR & STDOUT to different files. But first let create a simple script named “redirection.sh” to show how we can do the same
Here, ls –a /home/phony_directory will give us an error since there is no directory by that name & echo “Welcome dan” will print “Welcome dan ” to screen. Now let’s use redirection for this script.
Redirection of errors only
Run the script as follows
Now the errors for the script will be written inside “errors.txt ” file with use of 2>, where 2 is the file descriptor number for STDERR and > is the redirecting symbol. Successful output will be printed to screen.
Redirection of errors & output to different files
Run the script as follow
Here, 2> will redirect errors for the script to “errors.txt” & 1> will redirect output to “output.txt”
So, using this way we can redirect out output & errors. This concludes our tutorial. In our next tutorial, we will move to some advanced part of BASH scripting & will learn to create Functions for our script.
Leave your valuable comments/queries down below.