How to write output to file in Bash script [5 real examples] (2023)

Lal»Bash scripting tutorial»Bash scripting basics»28 Basic Bash Scripting Examples»How to write output to file in Bash script [5 real examples]

script bash

Practice of Islam Md Zahidul

August 24, 2023

Sometimes it is important to save the output of a command in a separate file. Also, errors may occur when executing commands. Writing errors or output to a file keeps the terminal tidy and makes it easier to review errors later. Bash provides useful functionsredirectTool to redirect command output and possible errors to the same or a different file. In this article, I'll show some bash scripts that redirect output to a file.

index expansion

main conclusion

  • The standard flow of commands.
  • Save output and errors to a file.
  • Append output and errors to a file.
  • Stop redirecting.

free download

Download exercise files

Understanding the Default Flow of Bash Commands

Bash commands generally have three default streams. You can control the flow of these standard streams and use the output of the commands efficiently.

standard output (stdout): This is the standard output stream where normal command output is sent. It is usually displayed in the terminal. Standard output is usually represented by a numeric descriptor1

standard error (stderr): This stream is used to display error messages and warnings. Standard errors are usually represented by numeric descriptors2

standard input (stdin): This stream receives the input data for the command. The numeric descriptor for this stream is0. Not all commands in Bash accept input.

How to write output to file in Bash script [5 real examples] (2)

In Bash, you can redirect these output streams to files in a number of ways.

5 Cases to Write Command Output to File Using Bash Script

A Bash script can contain multiple commands. You can save the output or errors of each command to a file. You can also save the general output of the script to a file.

Case 1: Writing output to a file using the > operator

First, I'll show you how to save the output of a command to a file using:>operator. The basic syntax for redirecting a command's standard output to a file is as follows:

command-name > file-name

This will run the command and save the output to the specified filename. Let's see how tohit hardroute map.

Steps to follow >

❶ First, start aUbuntuterminal

❷ Write the following command to open a file namedredirection.shunder constructionNanoedit:

nano-redirect.sh

explain

  • Nano: Opens the file in the Nano text editor.
  • redirection.sh: file name.
How to write output to file in Bash script [5 real examples] (3)

❸ Copy the following script and paste it inNano. according toCTRL+Oeentersave document;CTRL+Xgo out. Alternatively, copy the script below. Paste the script into a text editor and save it as.shdocument.

script (redirect.sh)>

#!/bin/bashecho "Current working directory: $(pwd)" > output.txt

explain

The script captures the current working directory withpassword command. It uses the echo command to echo the message "Current working directory:" after which the output ispasswordOrder. The message is then directed to an output file namedoutput.txtuse>Redirection operator.

❹ Use the following two commands to make these two filesexecutable file:

chmod u + x redirecionamento.sh

explain

  • chmod: Change permissions.
  • you+x: Grants execute permission to the owner.
  • redirection.sh: Screenplay name.
How to write output to file in Bash script [5 real examples] (4)

❺ execute oredirection.shWrite a script with the following command:

./redirect.sh

View the contents of the output file with the following command:

cat.txt output

How to write output to file in Bash script [5 real examples] (5)

oxygenoutput.txtThe expected output shown by the fileecologyepasswordThe command was successfully written to the file. Indicates that the current working directory is/home/raku

Case 2: Appending the output to a file using the >> operator

Now, if you want to append the output to an existing file, you can use>>operator. I will add some outputoutput.txtA file that already contains some content.

You can followCase 1 stepLearn how to create and save shell scripts.

Script (append.sh)>

#!/bin/bashecho "Current working directory folder:" >> output.txtls -d */ >> output.txt

explain

becomehit hardThe script appends a directory listing to an output file namedoutput.txt. The script starts usingecologyCommand to add message"Current working directory folder:" foroutput.txtdocument.

Thenls commandas-dThis option lists directories in the current working directory.*/Used to isolate directories from files. the result of thisEuropean UnionThen append the command tooutput.txtdocument.

execute oattachment.shWrite a script with the following command:

./append.sh

How to write output to file in Bash script [5 real examples] (6)

As you can see in the image above, the directory listing is appended to the existingoutput.txtdocument.

Case 3: Standard error written by 2> operator in Bash script

Commands can cause errors, which can be due to factors such as misspelled commands or invalid options. Error details are usually presented via the standard error stream rather than the standard output stream.

Normally, command errors in bash scripts are displayed in the terminal. However, standard error output can also be redirected to a specified file using2>operator.

You can followCase 1 stepLearn how to create and save shell scripts.

Screenplay (erro.sh) >

#!/bin/bashgrep "^SERVER=" /etc/ssmtp/ssmtp.conf 2> error.log

explain

oxygengrep commandFind lines that start with "server=" Nossmtp.conffiles in path/etc/ssmtp/ssmtp.conf. If it ends with an error, the error should be redirected toerror logdocument.

execute oerror.shWrite a script with the following command:

./error.sh

How to write output to file in Bash script [5 real examples] (7)

There was an error during program execution because it didn't show anythingterminal. oxygenerror logfile displaygrepcommand not foundssmtp.confThe file is located in the path provided. So it's a bug, and the error is correctly written inerror logFiled as expected.

observe:To include error messages in an existing file without overwriting its contents, use the following command2>>operator. This will append errors to the file without deleting previous data as new information is added.

Case 4: Writing or appending output or errors in the same file

Users may not be sure whether a command will cause an error or whether it will execute perfectly. In this case the user can redirect the output of the command and potential errors in the same file using2>&1operator.

You can followCase 1 stepLearn how to create and save shell scripts.

script (error_out.sh)>

#!/bin/bashdate > timelog.txt 2>&1date "%m-%d-%Y">> timelog.txt 2>&1

explain

O script US odate commandGets the current date and time, then transfers that information into a file namedtime log.txt. besides2>&1side to ensure that any possible error messagesdatacommands are also written to the same file.

Then the script repeatsdataCommands with custom formats“%m-%d-%Y”and append this formatted date totime log.txtand catch any potential errors.

execute oerror output.shWrite a script with the following command:

./error_out.sh

How to write output to file in Bash script [5 real examples] (8)

as you can see the firstdatacommand to write the current date intotime log.txtHowever, the second filedatacommand to write error messages to a file.

Use: &>Operators can be used instead2>&1.These two are essentially equivalent operators.

observe:It is also possible in Bash to redirect standard output to one file and standard error to another file.eco "linuxlimply.com" 2>std_err.txt 1>std_out.txtwrite the output tostandard output.txtand write the errorstd_err.txtIf any.

Case 5: Redirect output to file and terminal using Tee command

In addition to the above, users can also redirect the output of the command to a file at the same time, and view the output in the terminal to verify its correctness. oxygenserve orderis the appropriate tool to do this.

You can followCase 1 stepLearn how to create and save shell scripts.

Roadmap (tee.sh) >

/bin/bashls -a | #!/bin/bashls -a | grep "^\." | tee hidden files.txt

explain

The script usesEuropean Unioncommand to list all files in the current directory, including hidden files, and then usegrepcommand to filter hidden files, looking for lines starting with aView. oxygenT-shirtcommand is used to simultaneouslyterminaland save it in a file calledhidden file.txt

execute otee.shWrite a script with the following command:

./tee.sh

How to write output to file in Bash script [5 real examples] (9)

During execution, the program displays a list of hidden files in the current directory. I should write the same listhidden file.txtfiles too. Let us see its contents using the following commandcat command

How to write output to file in Bash script [5 real examples] (10)

Here you can see the same list is stored inhidden file.txtdocument.

observe:use|&pipeline syntaxstandard outputestandard errornot a commandT-shirtOrder.

Syntax of Multiple Redirections and Its Effects on Files and Terminals

The short list below contains the different syntaxesredirectoperators and whether they replace the contents of an existing file or simply add new information to it.

syntaxThe default output is visible

(no terminal)

terminal standard error

(no terminal)

The default output is visible

(in the file)

terminal standard error

(in the file)

Impact on Existing Files
>NosimulationsimulationNoreplace
>>NosimulationsimulationNoAdd to
2>simulationNoNosimulationreplace
2>>simulationNoNosimulationAdd to
&>NoNosimulationsimulationreplace
&>>NoNosimulationsimulationAdd to
| T-shirtsimulationsimulationsimulationNoreplace
| T-shirt-asimulationsimulationsimulationNoAdd to
|& shirtsimulationsimulationsimulationsimulationreplace
|& shirtsimulationsimulationsimulationsimulationAdd to

in conclusion

In summary, there are several operators in Bash script to redirect output to a file. You can use these operators to redirect output and errors to different files or to the same file. Additionally, you can handle redirection by changing the redirection descriptor. I believe that after reading this article, you will become a master of handling redirection operators in Bash.

people also ask

What should I do to redirect output to file and terminal?

you can use itT-shirtcommand redirects the output of the command to a file as well as to the terminal. This solution usually requirespipeline

How can I save the script output into a separate log file?

To save the output of the script to a file, redirect the output when running the script in the terminal. use./scriptname > filenamesave the output of the called scriptScreenplay nameforfile name

How to use Bash script output in another script?

using the output of ahit hardA script in another script calls the first script in another scriptsame process

rate this article

References

Top Articles
Latest Posts
Article information

Author: Manual Maggio

Last Updated: 13/01/2024

Views: 5884

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.