0

I am having trouble with using date as a variable in a bash script. I will admit that I have zero experience writing anything – in bash or otherwise – but I’ve been tasked with figuring this out. I have seen some other posts on here that come close to what I am looking for, but I haven’t been able to figure it out yet.

I need to move hundreds of log files from one directory to an archive directory named with the year and month (numerically) of last month, eg., 2016-07. I want the script to look in the archive directory to see if the directory for last month is there and, if not, create it and then move the logs into it. I’m using RHEL 5.11.

From the command prompt this gives me what I need:

date +%Y-%m –d “last month”

Which returns: 2016-07

I just can't get it work as a variable. I've tried the following (amongst other things):

last_month=date +%Y-%m -d "last month"
last month=(date +%Y-%m -d "last month")
dr_
  • 29,602

2 Answers2

-1

The magic word is "command substitution". From man bash:

Command substitution allows the output of a command to replace the command name.

$ d=$(date +%Y-%m -d "last month")
$ echo $d
2016-07
Murphy
  • 2,649
-2

Try this command:

$ last_month=`date +%Y-%m -d "last month"`
$ echo $last_month
dr_
  • 29,602
torer
  • 1