Home > Back-end >  BASH : Concatenate directory and generated filename
BASH : Concatenate directory and generated filename

Time:09-01

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

CodePudding user response:

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

CodePudding user response:

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

Worked as fine. The problem is that I forget to create the /var/log/cron directory.

  • Related