How to Use Date Command in Bash: Syntax and Examples
Use the
date command in bash to display or format the current date and time. You can customize the output by adding format options with +FORMAT, where format codes like %Y or %m represent year and month.Syntax
The basic syntax of the date command is:
date: Shows the current date and time.date +FORMAT: Displays the date/time formatted according toFORMAT.date -d "STRING": Shows the date/time for a specified date/time string.
Format codes start with % and represent parts of the date/time, like year, month, day, hour, minute, and second.
bash
date [+FORMAT]
date -d "STRING" [+FORMAT]Example
This example shows how to display the current date in Year-Month-Day format and how to get the date for tomorrow.
bash
date +"%Y-%m-%d" date -d "tomorrow" +"%Y-%m-%d"
Output
2024-06-15
2024-06-16
Common Pitfalls
Common mistakes include forgetting the + before the format string, which causes the command to print the literal string instead of formatting the date. Another is using unsupported format codes or incorrect date strings with -d.
Always enclose format strings in quotes to avoid shell interpretation issues.
bash
date "%Y-%m-%d" # Wrong: missing + date +"%Y-%m-%d" # Correct date -d "next week" +"%Y-%m-%d" # Correct usage of -d
Quick Reference
| Format Code | Meaning | Example Output |
|---|---|---|
| %Y | Year (4 digits) | 2024 |
| %m | Month (01-12) | 06 |
| %d | Day of month (01-31) | 15 |
| %H | Hour (00-23) | 14 |
| %M | Minute (00-59) | 30 |
| %S | Second (00-59) | 05 |
| %a | Abbreviated weekday | Sat |
| %A | Full weekday name | Saturday |
Key Takeaways
Use
date +FORMAT to customize date output with format codes.Always prefix format strings with
+ and enclose them in quotes.Use
date -d "STRING" to get dates for relative or specific times.Common format codes include
%Y for year, %m for month, and %d for day.Test your date commands to avoid syntax errors and unexpected outputs.