Input/Output redirection allows command line outputs to be passed into different streams. Three input/output streams are formed with codes for better usage. In this following blog post, you will learn what is Input/Output redirection in linux.
Standard Input (STDIN) :
STDIN are user inputs taken from the keyboard. When the user type some commands, the shell takes that data and interprets entered command syntax and then executes as command and gives the output or error. STDIN is identified with channel #0.
STDIN can be used for user interaction tasks in shell scripting with echo status code $0.
The stdin stream can be observed using “tr” command on the real time as mentioned below.
tr ‘a-z’ ‘A-Z’
Note : ‘tr’ command will not translate lower or upper case letters when we directly use it for file names.
However, if “<” redirection operator is used, this will converts lower case letters into upper case letters.
Standard Output (STDOUT) :
STDOUT are the outputs given by the shell after successful execution of given command. STDOUT is identified with channel #1.
In the below example, the output of echo is shown in the shell when “>” redirection operator is not used. After using “>” redirection operator, the output of echo is directed into the file named “file1”. If there is no file present in the name of file1, new file will be created with name “file1”.
echo “This is the first line in file1” > <filename>
The above command can be used along with 1 as below,
echo “This is the first line in file1” 1> <filename>
Both redirection operators 1> and > creates a new file containing standard output. If the specified file exists, it’s overwritten.
The redirection operator 1>> or >> appends standard output to the existing file. If the specified file doesn’t exist, it’s created.
Standard Error (STD ERR) :
STD ERR are the outputs which are given by the shell when the given command has error. STDERR can be redirected similarly to STDOUT. To prevent the error messages being displayed in the terminal, you should use 2> redirection operator.
cat <filename> 2> errorfile
The redirection operator 2>> appends standard error to the existing file. If the specified file doesn’t exist, it’s created.
Multiple streams:
After redirecting standard errors into error file, the standard outputs are still displayed in the terminal, to redirect both standard outputs and standard errors, &> is used.
ls -l <filename> <filename> &> errorfile1
How do you feel about this post? Drop your comments below..