Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 713
Alg_D Avatar asked Oct 24 '25 20:10

Alg_D


1 Answers

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).

like image 73
msbit Avatar answered Oct 26 '25 11:10

msbit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!