Linux – Redirect output to subfolders that don’t yet exist

bashcronlinux

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?

Best Answer

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.

Related Topic