Link to home
Start Free TrialLog in
Avatar of bemara57
bemara57

asked on

Adding date to bash script for cronjob.. Pls help

I'm trying to write a bash script that I can add to the cron. What I want to do is copy a folder and attach a date (any format is ok) to the end of it and put it in a backup folder. The only part I'm stuck on is creating the date as a variable and attach it to the folder name. This is what I'm trying to do on the Red Hat.

#!/bin/sh
cp dir_test /backup/dir_test_YYYY_MM_DD

After getting the date straight, I would just add this to /etc/crontab for update everyday at 6am right?
0 6 * * * /home/myscript.sh

I'm not sure if I even need a script file, can't I just put the command on the crontab itself? Thanks in advance for the. I just want to make sure I've got the right syntax and all.
SOLUTION
Avatar of MikeOM_DBA
MikeOM_DBA
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

-- Or by assigning date to variable:

#!/bin/bash
TODAY=`date  +%Y_%m_%d`
cp dir_test /backup/dir_test_$TODAY

Avatar of Julian Parker
you could assign the output from the date command, something like;

YY=`date +"%Y"`
MM=`date +"%M"`
DD=`date +"%D"`
cp dir_test  /backup/dir_test_${YY}_${MM}_${DD}

do a man on date for more formatting, that was from memory so it may be a touch inaccurate.

The crontab entry looks OK but you may have to enter the full path for the commands.

When I add entried into cron, I usually put the cron entry in /etc/cron.d like so
0 6 * * * root /home/myscript.sh

Hope this helps
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial