Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I currently redirect crontab script output to file in some folder that exists, like this:

echo "test" > `date "+/tmp/%Y%m%d_%H%M.log"`

I want to redirect output to subfolders, that maybe don't exists yet (.../year/month/..., so subfolders should be created:

echo "test" > `date "+/tmp/%Y/%m/%d_%H%M.log"`

How can I accomplish this?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Simply create the directory. The -p flag to mkdir achieves two things:

  • Create the entire path
  • Don't complain if the diretorry already exists

So:

mkdir -p  $(date "+/tmp/%Y/%m/") && echo "test" > $(date "+/tmp/%Y/%m/%d_%H%M.log")

Next time ask questions like this on unix.stackexchange please, it's a bit offtopic here.

share|improve this answer
    
I like one-liner with && + $(...) is nicer than `...`. Subquestion, If you know: canIi use multilines in crontab, like 5 * * * * command && \ (newline) command2 && \ (newline) command3? p.s. I will use unix.SO nexttime. –  glavić Feb 3 '13 at 16:08
    
If you want that, just wrap your commands in a small script and call the script from cron. –  Dennis Kaarsemaker Feb 3 '13 at 16:09

You need to create the folder(s) using mkdir -p command like:

mkdir -p `date "+/tmp/%Y/%m/"`

Then, you can execute your echo command safely.

echo "test" > `date "+/tmp/%Y/%m/%d_%H%M.log"`
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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