How to assign a formatted date to variable?

1

How can I create a datetime object, format it and assign it to a variable? The following does not work:

#!/usr/bin/env bash
time=14:00
timex = date -d "$time 5 minutes ago" +'%H:%M'
echo $timex

Result: line 3: timex: command not found. But why?

membersound

Posted 2017-06-12T14:37:33.300

Reputation: 135

Answers

0

Result: line 3: timex: command not found. But why?

There is a syntax error in your shell script and timex is not defined.

You can use ShellCheck to check for errors in your bash scripts:

$ shellcheck myscript

Line 3:
timex = date -d "$time 5 minutes ago" +'%H:%M'
^-- SC2037: To assign the output of a command, use var=$(cmd) .
      ^-- SC1068: Don't put spaces around the = in assignments.

Line 4:
echo $timex
     ^-- SC2154: timex is referenced but not assigned (did you mean 'time'?).
     ^-- SC2086: Double quote to prevent globbing and word splitting.

$ 

Try using the following script:

#!/usr/bin/env bash
time=14:00
timex=$(date -d "$time 5 minutes ago" +'%H:%M')
echo "$timex"

DavidPostill

Posted 2017-06-12T14:37:33.300

Reputation: 118 938