How to format date in YYYY-MM-DD format in Bash script

Last Updated on :April 21, 2024

Working with dates is a common task in scripting, especially in Bash. Whether you’re managing log files, scheduling tasks or simply displaying the current date in a specific format, understanding how to format dates is crucial. In this article, we’ll focus on formatting dates in the widely-used YYYY-MM-DD format using Bash scripts.

Basics of Date Command:

Bash provides a powerful built-in command called date that allows you to manipulate and format dates. Date Command will output the current date and time in the default format.

current_date=$(date)
echo "Current date: $current_date"

# Output - Current date: Fri Jan 26 22:39:02 IST 2024

Using the ‘+%Y-%m-%d’ Format:

When you use the +%Y-%m-%d format with the date command, it will display the current date in the format “year-month-day”.
Here’s how you can use it:


formatted_date=$(date '+%Y-%m-%d')
echo "Formatted date: $formatted_date"

# Output - Formatted date: 2024-01-26

Formatting a Specific Date:

If you need to format a specific date, you can pass it as an argument to the date command. For example, to format January 1, 2024:

specific_date="2024-01-01"
formatted_specific_date=$(date -jf "%Y-%m-%d" "$specific_date" '+%Y-%m-%d' 2>/dev/null)

if [ $? -eq 0 ]; then
  echo "Formatted specific date: $formatted_specific_date"
else
  echo "Error: Invalid date format. Please provide the date in YYYY-MM-DD format."
fi

Include Formatted Dates in Filenames:

One common use case for formatted dates is adding them into filenames. This is particularly handy when creating log files or backups. Here’s an example of how to create a file with the current date in the filename:

filename="backup_$(date '+%Y-%m-%d').tar.gz"
echo "Creating backup file: $filename"
# Actual backup command goes here

Output:


Creating backup file: backup_2024-01-19.tar.gz

Additional Resources
If you are interested in exploring more date formatting options or want to discover other available formats, you can refer to the `date` man pages for external non-bash specific commands. To access the man pages, simply type the following command in your terminal:


man date

You may also like...

Leave a Reply

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