bash 不带标点符号显示当前日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20551566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display current date and time without punctuation
提问by return 0
For example, I want to display current date and time as the following format:
例如,我想将当前日期和时间显示为以下格式:
yyyymmddhhmmss
How do I do that? It seems like most date format comes with -
, /
, :
, etc.
我怎么做?这似乎是大多数日期格式自带-
,/
,:
,等。
回答by janos
Here you go:
干得好:
date +%Y%m%d%H%M%S
As man date
says near the top, you can use the date
command like this:
正如man date
顶部附近所说,您可以使用如下date
命令:
date [OPTION]... [+FORMAT]
date [OPTION]... [+FORMAT]
That is, you can give it a format parameter, starting with a +
.
You can probably guess the meaning of the formatting symbols I used:
也就是说,您可以给它一个格式参数,以+
. 你大概可以猜到我使用的格式符号的含义:
%Y
is for year%m
is for month%d
is for day- ... and so on
%Y
是一年%m
是一个月%d
是一天- ... 等等
You can find this, and other formatting symbols in man date
.
您可以在man date
.
回答by Buru
A simple example in shell script
shell 脚本中的一个简单示例
#!/bin/bash
current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;
With out punctuation format :- +%Y%m%d%H%M%S
With punctuation :- +%Y-%m-%d %H:%M:%S
没有标点符号格式:- +%Y%m%d%H%M%S
有标点符号:- +%Y-%m-%d %H:%M:%S
回答by afaller
If you're using Bash you could also use one of the following commands:
如果您使用 Bash,您还可以使用以下命令之一:
printf '%(%Y%m%d%H%M%S)T' # prints the current time
printf '%(%Y%m%d%H%M%S)T' -1 # same as above
printf '%(%Y%m%d%H%M%S)T' -2 # prints the time the shell was invoked
You can use the Option -v varname
to store the result in $varname
instead of printing it to stdout:
您可以使用 Option-v varname
来存储结果$varname
而不是将其打印到标准输出:
printf -v varname '%(%Y%m%d%H%M%S)T'
While the date command will always be executed in a subshell (i.e. in a separate process) printf is a builtin command and will therefore be faster.
虽然 date 命令将始终在子 shell 中执行(即在单独的进程中) printf 是一个内置命令,因此会更快。
回答by Ani Menon
Without punctuation(as @Burusothman has mentioned):
没有标点符号(正如@Burusothman 提到的):
current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;
O/P:
开/关:
20170115072120
With punctuation:
标点符号:
current_date_time="`date "+%Y-%m-%d %H:%M:%S"`";
echo $current_date_time;
O/P:
开/关:
2017-01-15 07:25:33
回答by PesaThe
Interesting/funnyway to do this using parameter expansion(requires bash 4.4
or newer):
使用参数扩展(需要bash 4.4
或更新)来做到这一点的有趣/有趣的方法:
${parameter@operator} - P operator
The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string.
${parameter@operator} - P operator
扩展是一个字符串,它是将参数值扩展为提示字符串的结果。
$ show_time() { local format='\D{%Y%m%d%H%M%S}'; echo "${format@P}"; }
$ show_time
20180724003251