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

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

问题描述

我正在尝试在 shell 脚本中创建一个时间戳变量,以使日志记录更容易一些.我想在脚本开头创建变量,并在我发出 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")" echo 打印出 (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?

推荐答案

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

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,您可以在此处的官方文档中找到这些说明符的完整列表:https://www.gnu.org/software/coreutils/manual/html_node/Time-conversion-specifiers.html#Time-conversion-specifiers

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天全站免登陆