Alg_D
Alg_D

Reputation: 2390

Bash - how to format a time-stamp variable to human readable format

At the beginning of my script I set a variable DATE, which I need to use in different parts of the script and in different formats.

My issue is to use the same variable but format it in different ways:

#!/bin/bash
DATE=$(date +%s)
echo "date in timestamp format: $DATE"
echo "..."
# some other actions that need time...
echo "date start at: $(date $(DATE +%Y-%m-%d:%H:%M))"

this runs but outputs an error (DATE: command not found):

date in timestamp format: 1490884719
...
<script>.sh: line 6: DATE: command not found
date start at: Thu Mar 30 16:38:40 CEST 2017

how do I get rid of the error?

Upvotes: 4

Views: 5944

Answers (1)

msbit
msbit

Reputation: 4320

Using the $(...) is trying to execute the DATE command, without success. Coincidentally, date is running anyway, with no arguments, returning the current time (looking similar to the original).

Try replacing the whole line with something like:

echo "date start at: $(date --date=@${DATE} '+%Y-%m-%d:%H:%M')"

for GNU date (Linux and friends), and:

echo "date start at: $(date -j -f '%s' ${DATE} '+%Y-%m-%d:%H:%M')"

for BSD date (macOS and other BSDs).

Upvotes: 6

Related Questions