2015-11-13 24 views
1

我在shell中包含一個hour變量,其中包含UNIX時間(秒)。Linux shell表達式中的變量

然後如果要格式化這個時候,我用

date -u -d @$hour +"%Y-%m-%dT%H:%M:%S.000Z" 

其中工程。但是,我想將上述表達式的結果存儲到另一個變量中,所以當我這樣做時:

formatted=$((date -u -d @$hour +"%Y-%m-%dT%H:%M:%S.000Z")) 

它不起作用。我不知道如何在評估表達式中引用hour變量(不管它是否被調用)。

回答

11

表達

formatted=$((date -u -d @$hour +"%Y-%m-%dT%H:%M:%S.000Z")) 

使用哪隻適用於算術$((。雙括號更改爲單:

formatted=$(date -u -d @$hour +"%Y-%m-%dT%H:%M:%S.000Z") 

後者作品字符串

供參考(這些是POSIX外殼的功能,而不是慶典專用):

0

你可以做到這一點如下:

hour=1447409296 #Whatever timestamp value you want to set 
formatted=`date -u -d @$hour +"%Y-%m-%dT%H:%M:%S.000Z"` 
echo $formatted 

或:

formatted=`date -u -d @$hour +"%Y-%m-%dT%H:%M:%S.000Z"` 
1

您的command substitution語法錯誤微妙。在$之後使用雙括號在Bash中引入了一個非常明確的上下文,它被稱爲arithmetic context

所以只需放下一對括號即可。

formatted=$(date -u -d @$hour +"%Y-%m-%dT%H:%M:%S.000Z") 

反引號的使用在語法上是有效的,但discouraged

formatted=`date -u -d @$hour +"%Y-%m-%dT%H:%M:%S.000Z"` 
+0

添加勸阻方法的意義何在? – Bernhard

+0

@Bernhard因爲有人在另一個答案中提出。 – tripleee