How to Write the Output to a File in Bash Script [5 Practical Cases]

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.

Streams of input and output

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.

Steps to Follow >

❶ 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
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • redirect.sh: Name of the file.
Creating a Bash script using nano

❸ 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
EXPLANATION

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
EXPLANATION
  • chmod: Changes permissions.
  • u+x: Giving the owner executing permission.
  • redirect.sh: Name of the script.
Changing permission of Bash 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

Redirecting output to file

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.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (append.sh) >

#!/bin/bash

echo "Folders of current working directory:" >> output.txt
ls -d */ >> output.txt
EXPLANATION

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

Appending output in an existing file

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.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (error.sh) >

#!/bin/bash

grep "^SERVER=" /etc/ssmtp/ssmtp.conf 2> error.log
EXPLANATION

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

Saving error in a file

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.

NOTE: To include error messages in an existing file without overwriting its content, use the 2>> operator. This appends errors to the file, without removing the prior data while adding new information.

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.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (error_out.sh) >

#!/bin/bash

date > timelog.txt 2>&1
date "%m-%d-%Y">> timelog.txt 2>&1
EXPLANATION

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

Output and error in same file

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.

NOTE: &>  operator can used instead 2>&1. These two are essentially equivalent operators.
NOTE: Redirecting standard output in a file and standard error in a different file is also possible in Bash. echo “linuxlimply.com” 2> std_err.txt 1> std_out.txt will write the output in std_out.txt and write the error in std_err.txt if occurs any.

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.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (tee.sh) >

#!/bin/bash

ls -a | grep "^\." | tee hiddenfiles.txt
EXPLANATION

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

Output showing in terminal using tee command

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.

Saving output in file using tee command

Here you can see the same list is stored in the hiddenfiles.txt file.

NOTE: use |& syntax to pipe standard output and standard error of a command to the tee command.

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

What should I do to redirect output to both file and terminal?
You can use the tee command to redirect the output of a command to a file as well as to the terminal. This solution often requires piping.
How to save the output of the script in a separate log file?
To save the output of a script in a file, redirect the output while executing it in the terminal. Use ./scriptname > filename to save the output of the script called scriptname to filename.
How to use the output of the Bash script in another script?
To use the output of a Bash script in another script call the first script in the another script in a same process.

Related Articles


<< Go Back to Bash Script Examples | Bash Scripting Basics | Bash Scripting Tutorial

4.5/5 - (2 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment