Date and Time in Shell Scripting: Displaying the Current Date and Time in ‘YYYY-MM-DD HH:MM:SS’ Format

Shell Scripting @ Freshers.in

Working with date and time in shell scripting is essential for various tasks, such as logging, scheduling, and automation. One common requirement is to display the current date and time in a specific format. In this article, we will explore how to write a shell script that retrieves and displays the current date and time in the ‘YYYY-MM-DD HH:MM:SS’ format. We will cover the necessary commands and provide practical examples to help you understand and implement this functionality in your scripts.

Why Display Date and Time in a Custom Format?

Customizing the date and time format can be crucial for logging, record-keeping, or integrating timestamped data into filenames. The ‘YYYY-MM-DD HH:MM:SS’ format is human-readable and sortable, making it a popular choice for various applications.

Getting the Current Date and Time

To display the current date and time in the desired format, we can use the date command, which is available on most Unix-like systems.

Example 1: Displaying the Current Date and Time

You can retrieve the current date and time in the ‘YYYY-MM-DD HH:MM:SS’ format with the following command:

date "+%Y-%m-%d %H:%M:%S"

Output:

2024-01-18 15:30:45

Writing a Shell Script

To create a reusable shell script for displaying the current date and time in the specified format, follow these steps:

  1. Create a new file: Using your preferred text editor, create a new file named, for example, current_datetime.sh.
  2. Open the file: Open the file in your text editor and add the following lines:
#!/bin/bash
# This script displays the current date and time in 'YYYY-MM-DD HH:MM:SS' format.
current_datetime=$(date "+%Y-%m-%d %H:%M:%S")
echo "Current Date and Time: $current_datetime"
  1. Save the file: Save the file and exit your text editor.
  2. Make the script executable: In your terminal, navigate to the directory where you saved the script and make it executable using the following command:
chmod +x current_datetime.sh
  1. Run the script: Execute the script by running:
./current_datetime.sh

The script will display the current date and time in the desired format.

Author: user