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

蹲街弑〆低调 提交于 2021-01-18 06:23:26

问题


This question is pure curiosity. It is easy to get a date by running the date command from bash, but it is an external executable and requires spawning a subprocess. I wondered whether it is possible to get the current time/date formatted without a subprocess. I could only find references to date/time formats in the context of PS1 and HISTTIMEFORMAT. The latter allows this:

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

This comes close, but the $(history) spawns a subprocess, as far as I can tell.

Can we do better?


回答1:


bash 4.2 introduced a new specifier for printf; this was extended in bash 4.3 to use the current time if no argument is given. %()T expands to the current time, using the format appearing inside the parentheses.

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



回答2:


With Linux and 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"

Output:

2016-03-26 08:03:09


来源:https://stackoverflow.com/questions/36223881/getting-the-current-date-in-bash-without-spawning-a-sub-process

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!