在bash脚本中创建时间戳变量 [英] Create timestamp variable in bash script

查看:394
本文介绍了在bash脚本中创建时间戳变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Shell脚本中创建一个timestamp变量,以使记录变得更加容易.我想在脚本的开头创建变量,并在每次发布echo $timestamp时将其打印出当前时间.事实证明,这比我想的要困难得多.这是我尝试过的一些事情:

I am trying to create a timestamp variable in a shell script to make the logging a little easier. 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. It proving to be more difficult then I thought. Here are some things I've tried:

timestamp="(date +"%T")"回显打印出(date +"%T")

timestamp="$(date +"%T")" echo显示初始化变量的时间.

timestamp="$(date +"%T")" echo prints the time when the variable was initialized.

我尝试过的其他事情只是一些细微的变化,并没有取得更好的效果.有人知道我该怎么做吗?

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?

推荐答案

为了获得当前时间戳而不是定义固定变量的时间,诀窍是使用函数而不是 变量:

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" # current time
}

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

如果您不喜欢%T说明符给出的格式,则可以组合date接受的其他时间转换说明符.对于GNU date,您可以在以下官方文档中找到这些说明符的完整列表:

If you don't like the format given by the %T specifier you can combine the other time conversion specifiers accepted by 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

这篇关于在bash脚本中创建时间戳变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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