4

This question already has an answer here:

When I parameterize the date in the code as :

str_last_log_date="2017-07-24"
last_log_date=$(date -d '${str_last_log_date}' +%s)
threshold_days_ago=$(date -d 'now - 2 days' +%s)
echo "last_log_date ${last_log_date}  thres_days_ago ${threshold_days_ago}"

Gives the error :

date: invalid date ‘${str_last_log_date}’ last_log_date thres_days_ago 1500969455

But if I don't parameterize the date and pass directly, it gives the correct result :

last_log_date=$(date -d '2017-07-24' +%s)
threshold_days_ago=$(date -d 'now - 2 days' +%s)
echo "last_log_date ${last_log_date}  thres_days_ago ${threshold_days_ago}"

last_log_date 1500854400 thres_days_ago 1500969511

Any tips?

marked as duplicate by terdon shell-script Jul 27 '17 at 12:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3
last_log_date=$(date -d '${str_last_log_date}' +%s)

Should be updated to be (remove single quotes):

last_log_date=$(date -d ${str_last_log_date} +%s)
  • 1
    better yet, replace the single-quotes with double-quotes, so that it still works if $last_log_date is changed to contain a space (like "2017-07-24 21:16:00"). more re-usable too. – cas Jul 27 '17 at 11:18
  • 2
    @cas, or $IFS is modified to include - or : or digits... – Stéphane Chazelas Jul 27 '17 at 11:21
  • and, of course, the many other reasons why it's a good idea to always quote your variables – cas Jul 27 '17 at 12:28
6

Variables are not expanded when put inside single quotes; use double quotes instead:

date -d "${str_last_log_date}"

Not the answer you're looking for? Browse other questions tagged or ask your own question.