在不生成子进程的情况下获取 bash 中的当前日期

Getting the current date in bash without spawning a sub-process

这个问题纯属好奇。通过 运行 bash 的 date 命令很容易获得日期,但它是一个外部可执行文件,需要生成一个子进程。我想知道是否可以在没有子进程的情况下格式化当前的 time/date。我只能在 PS1HISTTIMEFORMAT 的上下文中找到对 date/time 格式的引用。后者允许这样做:

HISTTIMEFORMAT="%Y-%m-%d_%H:%M:%S "
history -s echo
x=$(history)
set -- $x
date=""

这很接近,但据我所知,$(history) 产生了一个子进程。

我们可以做得更好吗?

bash 4.2 为 printf 引入了一个新的说明符;如果没有给出参数,这在 bash 4.3 中被扩展为使用当前时间。 %()T 使用括号内显示的格式扩展到当前时间。

$ printf '%(%Y-%m-%d_%H:%M:%S)T\n'
2016-03-25_12:38:10

使用 Linux 和 GNU bash 4:

#!/bin/bash

while IFS=: read -r a b; do 
  [[ $a =~ rtc_time ]] && t="${b// /}"
  [[ $a =~ rtc_date ]] && d="${b// /}"
done < /proc/driver/rtc

echo "$d $t"

输出:

2016-03-26 08:03:09