0

This question already has an answer here:

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")

marked as duplicate by steeldriver, Stephen Harris, dr01, Jeff Schaller, sam Aug 5 '16 at 15:00

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.

  • last_month=$(date +%Y-%m -d "last month") - read man bash for details. – Satō Katsura Aug 5 '16 at 13:47
  • Thanks, Sato! That got me straight! Thank to Murphy, torer abd dr01, too! – saltycomms Aug 5 '16 at 14:34
-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
-2

Try this command:

$ last_month=`date +%Y-%m -d "last month"`
$ echo $last_month

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