# Using date in a shell script



## Pclinuxguru (Feb 28, 2013)

I have a backup script that backs up my /var/log/ folder daily. The backup names the tar file date-logs.tgz and works just fine. If I ran it today it would look like 28-Febuary-2013-logs.tgz.

What has me scratching my head is now I want to perform the backup monthly instead of daily. So I was thinking of having the crontab run the script on the beginning of the month however the date would put the current month in as the month when I would prefer the previous month in the file name.

So my monthly script would run tomorrow March 1st and the filename would be Febuary-2013-logs.tgz.

Here is an excerpt from the script:

```
#!/bin/sh
present=`date +'%d-%B-%Y'`

/usr/bin/tar cvzf /usr/LogTemp/$present-logs.tgz /var/log
```

Can anyone point me in the right direction?


----------



## SirDice (Feb 28, 2013)

Try adding -v -1m to the date command. That should subtract one month of the current date before calculating/formatting.


----------



## DutchDaemon (Feb 28, 2013)

The -v flag to date() is where to look.


```
date -v-1d +%d-%B-%Y
```

would give you yesterday's date, whereas


```
date -v-1m +%B-%Y
```

gives you last month.


----------



## luckystrike (Mar 30, 2015)

```
#!/bin/sh
/bin/date > /home/myhone/date.txt
#
for m in $(awk '{print $2}' /home/my-home/date.txt);do set m=$m;done
#
for d in $(awk '{print $3}' /home/my-home/date.txt);do mkdir /home/my-home/$m-$d && cd /home/my-home/$m-$d;done
#
```


----------



## tobik@ (Mar 30, 2015)

luckystrike said:


> ```
> #!/bin/sh
> /bin/date > /home/myhone/date.txt
> #
> ...


No. This does the same as your code, but is much easier to read and maintain:

```
today=$(date +%b-%d)
mkdir -p ~/$today
cd ~/$today
```
If you need to have date.txt add

```
echo $today > ~/date.txt
```


----------



## al3na66 (May 10, 2015)

Hi, can someone give me that script? I have an idea how to use it for my private server in case of emergency. Thanks a lot.


----------

