Write Output of Bash Command to Log File

To write output of Bash Command to Log File, you may use right angle bracket symbol (>) or double right angle symbol (>>).

Right angle braketsymbol (>) : is used to write output of a bash command to a disk file. If the file is not already present, it creates one with the name specified. If the file is already present, the content of the file would be overwritten.

Double right angle symbol (>>) : is used to append data to an existing file. If the file is not already present, a new one would be created.

When you are writing to the file for the first time, and want no previous data to be in the file if it is already present, use (>) to make sure that it overwrites the content. And in the later script, you may use (>>) to append to the log file.

Example

Following is an example to demonstrate writing output of Bash Commands to Log File.

Bash Script File

</>
Copy
#!/bin/bash

log=log_file.txt

# create log file or overrite if already present
printf "Log File - " > $log

# append date to log file
date >> $log

x=$(( 3 + 1 ))
# append some data to log file
echo value of x is $x >> $log

When you run the above bash script, following file would be created with the content specified.

log_file.txt

Log File - Fri Dec 15 11:47:03 IST 2017
value of x is 4

Conclusion

In this Bash Tutorial, we learned how to write the output of a Bash command to a file.