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. 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 prints out (date +"%T")
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"
}
# 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
. 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
If you want to get unix timestamp, then you need to use:
timestamp=$(date +%s)
%T
will give you just the time; same as %H:%M:%S
(via http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/)
DATE=`date "+%Y%m%d"`
DATE_WITH_TIME=`date "+%Y%m%d-%H%M%S"` #add %3N as we want millisecond too
链接地址: http://www.djcxy.com/p/29118.html
上一篇: 为什么有时在元字符周围需要空格?
下一篇: 在bash脚本中创建时间戳变量