Linux provides an inbuilt command for checking the current time and date. The command date is used to get this information on a terminal.

$ date
Sun Aug 13 19:06:12 IST 2023

How to use date command ?

There are instances wherein, you want to run a certain command repeatedly and want to capture the output logs of that command. For this you have to give the log file a name every time you run the command.
This repeated step can be avoided by using the date command. Instead of specifying a new name for the log file while running the command. We can automatically fetch the current date and time from the date command and use that as a file name to store the logs.

This can be done as follows. In the below example, we are using a shell script to run a command and use the date command along with the actual command to save the logs.

#! /bin/bash

curr_time=$(date "+%Y.%m.%d-%H.%M.%S")
echo $curr_time

echo "start docker-compose"
docker-compose up | tee $curr_time-compose.log
echo "done.."

In the above shell script, we are storing the current date and time in a variable called curr_time and using that variable later in the actual command to save the logs with the date and time.
NOTE: When tee is used the output is shown on the terminal and logs are written to file in parallel.

This need not be a shell script, we can just use the command directly on the terminal as well.

ls -ltr | tee $(date "+%Y.%m.%d-%H.%M.%S").log

Leave a Reply

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

Verified by MonsterInsights