Bash Scripting-11-Input Output redirection in Linux — The Linux GURUS
Though not a part of scripting only, input output redirection in Linux can be used for other purposes as well. Now before we discuss about input output redirection in Linux in detail. Let’s discuss about redirecting the output of a script to a file.
Recommended Read: Bash Scripting-11-Input Output redirection in Linux
Also Read: How to setup SSH login without password on Linux systems
Redirect output of script to file
It’s easy to redirect output of script to file, let’s discuss an example of this,
#!/bin/bash echo “ Please enter the full path of file/directory (ex- /home/dan.new.txt)” read path for file in $path do if [ -d “$file” ] then echo “$file is a directory” elif [ -f “$file” ] then echo “$file is a file” else echo “No file found”
In the last line, we redirected the output to a file named ‘result.txt’. Now let’s discuss about input output redirection in Linux
Input Output redirection in Linux
Every object in Linux is treated as a file & every file is identified as a file descriptor. 3 out of these 9 file descriptors are reserved by bash, their list is as follows,
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 let’s discuss input output redirection in Linux with an example,
ls -a /home/example_directory
In this simple script, we used two commands, first command will throw output as there is no directory by that name & then second command will run successfully. Now let’s see how to handle the errors & successful outputs to files.
Redirection of errors only
Run the script as follows
$ sh redirection.sh 2 > errors.txt
Now the successful output will be printed on screen & the error message will go to a file.
Redirection of errors & output to different files
Run the script as follow
$ sh redirection.sh 2 > errors.txt 1> output.txt
Here, 2 > will redirect errors for the script to “errors.txt” & 1> will redirect output to “output.txt”. With this our tutorial is complete, send any suggestions, queries or questions using the comment box below.
If you think we have helped you or just want to support us, please consider these:-
TheLinuxGURUS are thankful for your continued support.
Originally published at https://thelinuxgurus.com on January 13, 2020.