本文翻譯自: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實現中都使用當前時間戳。