Search code examples
phplinuxbashcroncron-task

BASH : Concatenate directory and generated filename


I have a command in a CRONTAB like php artisan mycommand:test .

I want to write the output of my command into a daily generated filename like /var/log/cron/command-logs-2022-09-01.log.

I did something like :

php artisan mycommand:test >> `date +"%Y-%m-%d"`\ `date +"H:%M:%S"`.log

And It worked perfectly. (filename like 2022-09-01 08:34:03.log)

But when I add a directory before the filename it gives me No such file or directory

php artisan mycommand:test >> '/var/log/cron/'`date +"%Y-%m-%d"`\ `date +"H:%M:%S"`.log
bash: '/var/log/cron/'`date +"%Y-%m-%d"`\ `date +"H:%M:%S"`.log: No such file or directory

Solution

  • $ echo "php artisan mycommand:test >> '/var/log/cron/'`date +"%Y-%m-%d"`\ `date +"H:%M:%S"`.log"
    php artisan mycommand:test >> '/var/log/cron/'2022-09-01\ H:44:03.log
    

    Hence modify this to:

    $ echo "php artisan mycommand:test >> /var/log/cron/'`date +"%Y-%m-%d"`_`date "+H:%M:%S"`.log"
    php artisan mycommand:test >> /var/log/cron/'2022-09-01_H:44:40.log
    

    Use:

    $ php artisan mycommand:test >> /var/log/cron/`date +"%Y-%m-%d"`_`date "+H:%M:%S"`.log
    

    OR:

    $ php artisan mycommand:test >> /var/log/cron/$(date +"%Y-%m-%d")_$(date "+H:%M:%S").log
    

    Sample output:

    $ echo "php artisan mycommand:test >> /var/log/cron/$(date +"%Y-%m-%d")_$(date "+H:%M:%S").log"
    php artisan mycommand:test >> /var/log/cron/2022-09-01_H:47:08.log
    

    if Not having /var/log/cron/ directory

    php artisan mycommand:test >> /var/log/cron_$(date +"%Y_%m_%d_%H_%M_%S.log")