log shell script output to file

How to Log Shell Script Output to File

Sometimes you may need to write the output of your shell script to a file, or redirect its output to a file. In this article, we will look at how to log shell script output to file.


How to Log Shell Script Output to File

Here are the steps to log shell script output to file.


1. Create empty shell script

Open terminal and run the following command to create an empty shell script.

$ sudo vi test.sh


2. Write Output to File

Add the following lines at the top of your shell script to write the output to a file /output.txt. Replace this path with the file path of your choice.

#!/bin/bash
exec > /output.txt 2>&1

The exec command above will save shell script’s output to /output.txt file.

Then add your shell script’s code below as shown.

#!/bin/bash
exec > /output.txt 2>&1

echo "Start logging out from here to a file" 
echo "something happening"
echo "End logging out from here to a file"

Save and close the file.


3. Make shell script executable

Run the following command to make shell script executable.

$ sudo chmod +x test.sh


4. Test shell script

Run the shell script as shown.

$ ./test.sh

You will see the following output in terminal

Start logging out from here to a file
something happening
End logging out from here to a file

Now open the file /output.txt

$ cat /output.txt

You will see the following content of your file as, indicating that the output of your shell script has been written to it.

Start logging out from here to a file
something happening
End logging out from here to a file

Also read:

Find PID of Process Running on Port
How to Check if Port is Open or Closed in Linux
How to Determine Linux Kernel Architecture
How to List All Cron Jobs of All Users
How to Check Crontab Logs in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *