Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting date of X days ago in bash script, using argument variable

Tags:

I'm trying to calculate the date for a dynamic number of days ago in a bash script.

This is what I've done -

#!/bin/bash
STAMP=`date --date='$1 day ago' +%y%m%d`

but when running myscript 2, it says -

date: invalid date `$1 day ago'

How can I use my argument value in this formula?

like image 918
Kof Avatar asked Aug 05 '13 14:08

Kof


People also ask

What does %% mean in bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.


2 Answers

It works if ' is replaced with " into this command on the script -

STAMP=`date --date="$1 day ago" +%y%m%d`

The clue was the two different character ` and ' used in the error response -

date: invalid date `$1 day ago'

An expert in bash scripting (not me) can probably explain why this has happen.

like image 174
Kof Avatar answered Oct 20 '22 17:10

Kof


It's because variable substitution wouldn't happen in single quotes, i.e. '$1' wouldn't expand but "$1" would.

As such, saying

STAMP=`date --date="$1 day ago" +%y%m%d`

or

STAMP=$(date --date="$1 day ago" +%y%m%d)

would work.

like image 43
devnull Avatar answered Oct 20 '22 19:10

devnull