在 bash 中获取当前日期而不产生子进程 [英] Getting the current date in bash without spawning a sub-process

查看:12
本文介绍了在 bash 中获取当前日期而不产生子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
'
2016-03-25_12:38:10

这篇关于在 bash 中获取当前日期而不产生子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆