1

I have an hour variable in shell that contains UNIX time in seconds.

Then If want to format this hour, I use

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

which works. However, I want to store the result of the above expression to another variable, so when I do:

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

it does not work. I do not know how will I reference the hour variable within an evaluation expression (whatever it is called).

3 Answers 3

12

The expression

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

use the $(( which works only for arithmetic. Change the double parentheses to single:

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

The latter works for strings.

For reference (these are POSIX shell features, not bash-specific):

Sign up to request clarification or add additional context in comments.

Comments

1

Your syntax for command substitution is subtly wrong. The use of double parentheses after $ introduces a quite distinct context in Bash, which is known as arithmetic context.

So just drop one pair of parentheses.

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

The use of backticks is syntactically valid, but discouraged.

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

Comments

0

You can do it as following:

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

or:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.