When working with shell scripts, it’s often necessary to display or store the current date in a specific format. One of the most commonly used formats is YYYY-MM-DD, which represents the year, month, and day of the month, respectively. In this tutorial, we’ll explore how to achieve this in a bash shell script.
The date
command is typically used to print the current date and time. However, by default, it doesn’t produce the desired YYYY-MM-DD format. To get the date in this format, you can use the date
command with a specific format specifier.
One way to do this is by using the +
symbol followed by the format string. For example, to get the current date in YYYY-MM-DD format, you can use the following command:
date '+%Y-%m-%d'
Here, %Y
represents the year in four digits, %m
represents the month as a zero-padded decimal number, and %d
represents the day of the month as a zero-padded decimal number.
Alternatively, you can use the %F
format specifier, which is an alias for %Y-%m-%d
. This makes the command even simpler:
date '+%F'
If you want to include the time in the output, you can add additional format specifiers. For example, to get the current date and time in YYYY-MM-DD HH:MM:SS format, you can use:
date '+%Y-%m-%d %H:%M:%S'
In bash version 4.2 and later, you can also use the printf
command with a built-in date formatter to achieve the same result:
printf '%(%Y-%m-%d)T\n' -1
This method is preferred over using the external date
command, as it avoids the overhead of invoking a subshell.
To store the formatted date in a variable, you can use command substitution:
date_string=$(date '+%Y-%m-%d')
You can then use the $date_string
variable in your script as needed.
In summary, formatting dates in shell scripts is straightforward using the date
command with format specifiers. By choosing the right format string, you can easily get the current date in the desired YYYY-MM-DD format.