简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM