FUNDAMENTALS A Complete Guide for Beginners
Sometimes, it’s important to save a command’s output in a separate file. Moreover, an error may occur while executing a command. Writing errors or output to file keeps the terminal tidy and makes it easier to review errors later. Bash provides useful redirection tools to redirect command output and potential errors to the same or different files. In this article, I will show you few bash script to redirect output to file.
Key Takeaways
- Standard streams of a command.
- Saving output and error in a file.
- Appending Output and error in a file.
- Halting Redirection.
Free Downloads
Understanding Standard Streams of a Bash Command
Bash commands typically have three standard streams. One can control the flow of these standard streams and efficiently use the output of a command.
Standard Output (stdout): This is the default output stream where normal command output is sent. It’s usually displayed on the terminal. The standard output is usually represented by the numeric descriptor 1.
Standard Error (stderr): This stream is used to display error messages and warnings. The standard error is usually represented by the numeric descriptor 2.
Standard Input (stdin): This stream receives input data to a command. The numeric descriptor for this stream is 0. Not all commands in Bash receive input.
In Bash, you can redirect these output streams to files using various methods.
5 Cases of Writing Commands Output to File Using Bash Script
A Bash script may contain multiple commands within it. You can save the output or error of each of those commands into files. You can also save the overall output of a script into a file.
Case 1: Writing Output to a File Using “>” Operator
First of all, I am going to show you how to save a command’s output to a file using the > operator. The basic syntax of redirecting the standard output of a command into the file is as follows:
command_name > filename
This will execute the command and saves the output in the specified filename. Let’s see how to use this operator in a Bash script.
❶ At first, launch an Ubuntu Terminal.
❷ Write the following command to open a file named redirect.sh in the build-in nano editor:
nano redirect.sh
- nano: Opens a file in the Nano text editor.
- redirect.sh: Name of the file.
❸ Copy the following scripts and paste them into nano. Press CTRL+O and ENTER to save the file; CTRL+X to exit. Alternatively, copy the following script. Paste the script in a text editor and save it as .sh file.
Script (redirect.sh) >
#!/bin/bash
echo “Current Working directory: $(pwd)” > output.txt
This script captures the current working directory using the pwd command. It uses the echo command to echo a message “Current Working directory:” followed by the output of pwd command. This message is then directed into an output file named output.txt using the > redirection operator.
❹ Use the following two commands to make both file executable:
chmod u+x redirect.sh
- chmod: Changes permissions.
- u+x: Giving the owner executing permission.
- redirect.sh: Name of the script.
❺ Run the redirect.sh script by the following command:
./redirect.sh
See the content of the output file by the command below:
cat output.txt
The output.txt file shows that the intended output of echo and pwd commands is successfully written in the file. It shows the current working directory is /home/laku.
Case 2: Appending Output to a File Using “>>” Operator
Now if you want to add output to an existing file you can use the >> operator. I am going to add some output in the output.txt file that already contains some contents in it.
Script (append.sh) >
#!/bin/bash
echo "Folders of current working directory:" >> output.txt
ls -d */ >> output.txt
This Bash script appends a list of directories to an output file named output.txt. The script begins by using the echo command to add a message “Folders of current working directory:” to the output.txt file.
Then the ls command with the -d option lists directories of the current working directory. */ is used to isolate directories from files. The result of this ls command is then appended to the output.txt file.
Run the append.sh script by the following command:
./append.sh
As you can see in the image above a list of directories is appended with the existing content of the output.txt file.
Case 3: Writing Standard Error by “2>” Operator in Bash Script
A command may end up with an error, which can occur due to factors like command misspellings or invalid options. The error details are usually presented through the standard error stream rather than the standard output stream.
Usually, an error in command within a bash script is shown in the terminal. However, it is also possible to redirect the standard error output to a designated file using the 2> operator.
Script (error.sh) >
#!/bin/bash
grep "^SERVER=" /etc/ssmtp/ssmtp.conf 2> error.log
The grep command search for lines that begin with “SERVER=” in the ssmtp.conf file in the path /etc/ssmtp/ssmtp.conf. If it ends up with an error, then the error should be redirected to the error.log file.
Run the error.sh script by the following command:
./error.sh
Error occurs while executing the program as it shows nothing in the terminal. The error.log file shows that the grep command didn’t find any ssmtp.conf file in the given path. So, its an error and the error is properly written in the error.log file as expected.
Case 4: Writing or Appending Output or Error in the Same File
A user may not be sure about whether a command ends up with an error or it will be executed perfectly. In such a scenario, the user can redirect the output of a command and the potential error in the same file using the 2>&1 operator.
Script (error_out.sh) >
#!/bin/bash
date > timelog.txt 2>&1
date "%m-%d-%Y">> timelog.txt 2>&1
The script uses the date command to obtain the current date and time and then directs this information to the file named timelog.txt. Additionally, the 2>&1 part ensures that any potential error messages from the date command are also written to the same file.
The script then repeats the date command with a custom format “%m-%d-%Y” and appends this formatted date to the timelog.txt and also captures any potential error.
Run the error_out.sh script by the following command:
./error_out.sh
As you can see the first date command writes the current date in the timelog.txt file. However, the second date command writes an error message in the file.
Case 5: Redirecting Output to a File and Terminal Using the “tee” Command
Apart from the above cases a user can simultaneously redirect the output of a command to a file as well as visualize the output in terminal to check its correctness. The tee command is the appropriate tool to do this.
Script (tee.sh) >
#!/bin/bash
ls -a | grep "^\." | tee hiddenfiles.txt
The script employs the ls command to list all files in the current directory, including hidden ones, and then utilizes grep command to filter out hidden files by searching for lines starting with a dot. The tee command is used to simultaneously display this filtered output in the terminal and save it to a file named hiddenfiles.txt.
Run the tee.sh script by the following command:
./tee.sh
While executing the program shows the list of hidden files of the current directory. It should write the same list in the hiddenfiles.txt file as well. Let’s see its content using the cat command.
Here you can see the same list is stored in the hiddenfiles.txt file.
Syntax of Various Redirection and Their Effect on File and Terminal
The brief list below contains syntax of different redirection operators and whether they overwrite the contents of an existing file or just append new info in it.
Syntax | Visible StdOut
(In Terminal) |
Terminal StdErr
(In Terminal) |
Visible StdOut
(In File) |
Terminal StdErr
(In File) |
Effect on Existing File |
---|---|---|---|---|---|
> | no | yes | yes | no | Overwrite |
>> | no | yes | yes | no | Append |
2> | yes | no | no | yes | Overwrite |
2>> | yes | no | no | yes | Append |
&> | no | no | yes | yes | Overwrite |
&>> | no | no | yes | yes | Append |
| tee | yes | yes | yes | no | Overwrite |
| tee -a | yes | yes | yes | no | Append |
|& tee | yes | yes | yes | yes | Overwrite |
|& tee | yes | yes | yes | yes | Append |
Conclusion
In summary, there are multiple operators in Bash scripting to redirect output to a file. You can use these operators to redirect output and errors to different or the same file. Additionally, you can manipulate redirection by changing redirection descriptors. I believe that after reading this article, you will become a master at handling redirection operators in Bash.
People Also Ask
Related Articles
- How to Get Date in Bash [2 Methods with Examples]
- How to Print Time in Bash [2 Quick Methods]
- How to List Users in Bash [2 Easy Ways]
- How to Get Current Time in Bash [4 Practical Cases]
- How to Use Date Format in Bash [5 Examples]
- How to Get Timestamp in Bash [2 Practical Cases]
- How to Copy and Paste in Bash [2 Methods & Cases]
- How to Read Password in Bash [3 Practical Cases]
- How to Send Email in Bash [2 Easy Methods]
- Bash Script to Send Email with Attachment [Step-by-Step Guide]
- How to Get IP Address in Bash [3 Methods]
- How to Find and Replace String in Bash [5 Methods]
- How to Get Script Name Using Bash Script? [3 Easy Ways]
- How to Call Another Script in Bash [2 Methods]
- How to Generate UUID in Bash [3 Simple Methods]
- 3 Easy Ways to Write to a File in Bash Script
- How to Create a List in Bash Scripts? [2 Easy Methods]
- How to Clear History in Bash [2 Practical Cases]
- How to Clear Screen Using Bash Script? [2 Effective Methods]
- How to Check Ubuntu Version Using Bash Scripts? [2 Methods]
<< Go Back to Bash Script Examples | Bash Scripting Basics | Bash Scripting Tutorial