简体   繁体   English

关于在Linux Shell脚本中打印格式化的Datetime

[英]About Print formated Datetime in linux shell scripts

After i type: date +"%y-%m-%d %H:%M:%S" in linux shell i get the right result such as: 14-09-26 10:47:28. 我在linux shell中键入:date +“%y-%m-%d%H:%M:%S”后,我得到了正确的结果,例如:14-09-26 10:47:28。

However, when i want to get the result in a shell script, I get a error : "date: illegal time format", Why? 但是,当我想在shell脚本中获取结果时,出现错误:“日期:非法时间格式”,为什么?

#!/bin/sh

STR='date +"%y-%m-%d %H:%M:%S"'

echo "`$STR`"

The trouble with: 问题在于:

#!/bin/sh

STR='date +"%y-%m-%d %H:%M:%S"'

echo "`$STR`"

is that when the string is executed in the echo command, the date command sees three arguments: 当在echo命令中执行字符串时, date命令将看到三个参数:

date
+%y-%m-%d
%H:%M:%S

It is trying to interpret the %H:%M:%S as a date/time in the format: 它试图将%H:%M:%S为日期/时间,格式为:

[[[mm]dd]HH]MM[[cc]yy][.ss]]

or: 要么:

mmddhhmm[[cc]yy]

or: 要么:

[MMDDhhmm[[CC]YY][.ss]]

(the first from Mac OS X date , the second from POSIX, the third from GNU date ). (第一个来自Mac OS X date ,第二个来自POSIX,第三个来自GNU date )。 In those, the pairs of letters represent components of the date to be set as the time. 在这些字母中,字母对表示要设置为时间的日期的组成部分。 Since the %H:%M:%S string contains no digits, it is an invalid date format. 由于%H:%M:%S字符串不包含数字,因此它是无效的日期格式。

How could you work around this? 您如何解决这个问题?

It depends in part on whether /bin/sh is Bash, Korn shell, Dash, Bourne shell or some other shell. 它部分取决于/bin/sh是Bash,Korn Shell,Dash,Bourne Shell还是其他外壳。

The simplest solution should work in all but the oldest Bourne shells, and that is to create a function: 除最旧的Bourne外壳外,最简单的解决方案应能在所有外壳中使用,即创建一个函数:

dt() { date +'%Y-%m-%d %H:%M:%S'; }

You can then use: 然后,您可以使用:

echo "$(dt)"

using the $(…) notation in preference to back-ticks. 优先使用$(…)表示法而不是反引号。

Note that I decline to use %y ; 注意,我拒绝使用%y I remember the Y2K bug, even if you're too young to have been involved in the remediation work. 我记得Y2K的错误,即使您还太小而无法参与补救工作。

An alternative technique requires support for arrays (Bash, Korn shells, but not Dash or Bourne): 另一种技术要求支持数组(Bash,Korn shell,但不支持Dash或Bourne):

STR=( date +"%Y-%m-%d %H:%M:%S" )

echo "$( "${STR[@]}" )"

or, more simply: 或者,更简单地说:

"${STR[@]}"

Try excecuting at the assignment iteself. 尝试自己执行任务。

 $ #!/bin/sh

   $ STR=`date +"%y-%m-%d %H:%M:%S"`

   $ echo $STR
  14-09-26 11:40:06

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM