在bash中获取当前日期而不生成子流程 [英] Getting the current date in bash without spawning a sub-process
问题描述
这个问题纯粹是出于好奇.通过从bash运行 date
命令很容易获得日期,但是它是一个外部可执行文件,需要生成一个子进程.我想知道是否有可能在没有子流程的情况下格式化当前时间/日期.我只能在 PS1
和 HISTTIMEFORMAT
的上下文中找到对日期/时间格式的引用.后者允许这样做:
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"
这很接近,但是据我所知, $(history)
产生了一个子进程.
This comes close, but the $(history)
spawns a subprocess, as far as I can tell.
我们可以做得更好吗?
推荐答案
bash
4.2为 printf
引入了新的说明符;如果未指定任何参数,则在 bash
4.3中进行了扩展,以使用当前时间.%()T
使用括号内显示的格式扩展到当前时间.
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
这篇关于在bash中获取当前日期而不生成子流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!