# put current date as yyyy-mm-dd in $date# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided# -2 -> start time for shellprintf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $dateprintf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such:printf '%(%Y-%m-%d)T\n' -1# -> current date printed to terminal
在bash(<4.2)中:
# put current date as yyyy-mm-dd in $datedate=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $datedate=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directlyecho $(date '+%Y-%m-%d')
$ printf '%(%Y-%m-%d)T\n' -1 # Get YYYY-MM-DD (-1 stands for "current time")2017-11-10$ printf '%(%F)T\n' -1 # Synonym of the above2017-11-10$ printf -v date '%(%F)T' -1 # Capture as var $date
printf比date快得多,因为它是一个Bash内置,而date是一个外部命令。
同样,printf -v date ...比date=$(printf ...)快,因为它不需要分叉子shell。
#!/bin/bash -e
x='2018-01-18 10:00:00'a=$(date -d "$x")b=$(date -d "$a 10 min" "+%Y-%m-%d %H:%M:%S")c=$(date -d "$b 10 min" "+%Y-%m-%d %H:%M:%S")#date -d "$a 30 min" "+%Y-%m-%d %H:%M:%S"
echo Entered Date is $xecho Second Date is $becho Third Date is $c