在bash脚本中创建时间戳变量

本文翻译自:Create timestamp variable in bash script

I am trying to create a timestamp variable in a shell script to make the logging a little easier. 我正在尝试在shell脚本中创建一个timestamp变量,以使记录变得更加容易。 I want to create the variable at the beginning of the script and have it print out the current time whenever I issue echo $timestamp . 我想在脚本的开头创建变量,并在每次发出echo $timestamp时将其打印出当前时间。 It proving to be more difficult then I thought. 事实证明,这比我想的要困难得多。 Here are some things I've tried: 这是我尝试过的一些方法:

timestamp="(date +"%T")" echo prints out (date +"%T") timestamp="(date +"%T")" echo输出(date +"%T")

timestamp="$(date +"%T")" echo prints the time when the variable was initialized. timestamp="$(date +"%T")" echo显示变量初始化的时间。

Other things I've tried are just slight variations that didn't work any better. 我尝试过的其他内容只是一些细微的变化,效果并不理想。 Does anyone know how to accomplish what I'm trying to do? 有谁知道我该怎么做?


#1楼

参考:https://stackoom.com/question/19bi6/在bash脚本中创建时间戳变量


#2楼

使用命令替换:

timestamp=$( date +%T )

#3楼

In order to get the current timestamp and not the time of when a fixed variable is defined, the trick is to use a function and not a variable: 为了获得当前时间戳而不是定义固定变量的时间,技巧是使用函数而不是变量:

#!/bin/bash

# Define a timestamp function
timestamp() {
  date +"%T"
}

# do something...
timestamp # print timestamp
# do something else...
timestamp # print another timestamp
# continue...

If you don't like the format given by the %T specifier you can combine the other time conversion specifiers accepted by date . 如果您不喜欢%T说明符给出的格式,则可以结合date接受的其他时间转换说明符。 For GNU date , you can find the complete list of these specifiers in the official documentation here: https://www.gnu.org/software/coreutils/manual/html_node/Time-conversion-specifiers.html#Time-conversion-specifiers 对于GNU date ,您可以在以下官方文档中找到这些说明符的完整列表: https : //www.gnu.org/software/coreutils/manual/html_node/Time-conversion-specifiers.html#Time-conversion-specifiers


#4楼

If you want to get unix timestamp, then you need to use: 如果要获取unix时间戳,则需要使用:

timestamp=$(date +%s)

%T will give you just the time; %T会给你时间。 same as %H:%M:%S (via http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/ ) %H:%M:%S (通过http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/


#5楼

You can use 您可以使用

timestamp=`date --rfc-3339=seconds`

This delivers in the format 2014-02-01 15:12:35-05:00 此格式为2014-02-01 15:12:35-05:00

The back-tick ( ` ) characters will cause what is between them to be evaluated and have the result included in the line. 反引号( ` )字符将导致对它们之间的内容进行评估,并将结果包括在该行中。 date --help has other options. date --help还有其他选项。


#6楼

timestamp=$(awk 'BEGIN {srand(); print srand()}')

没有值的srand在大多数Awk实现中都使用当前时间戳。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值