1

I'm trying to output the current date in this format to a file using /etc/crontab. But crontab doesn't like this formatting. Changing sh to bash doesn't help.

my crontab:

* * * * * root echo "$(date +%F) - $(date +%T) - no sleep!" >> /home/thomas/1-18-WD/ami

expected output to the file: 2021-05-18 - 03:57:09 - no sleep!

it only works if I just do echo "$(date) - no sleep!" The "+" is causing the problem I think.

2 Answers2

0

Jobs run through cron, or at, or batch, aren't run in the same runtime environment that you have on your desktop. None of your PATH changes, or other environment variable settings are automatically propagated to your cron job. For example, there's no $DISPLAY, so GUI programs need special treatment (read man xhost).

One can set environment variables for all one's cron jobs in the crontab file Read man 5 crontab.

Look at the results of echo "=== set ===";set;echo "=== env ===";env | sort;echo "=== alias ===";alias in each of your environments.

Since the command part of the crontab line is, by default, interpreted by /bin/sh, which has a simpler syntax than /bin/bash, I recommend having command be a call to a bash script (executable, mounted, starts with7 #!/bin/bash) which sets up the environment, then calls the desired program.

waltinator
  • 36,399
0

It's not the + character that's the problem here - it's the % character(s), as explained here:

However you can simplify the command and avoid 2 calls to date and the echo by moving your text into the date format string directly, i.e. date "+%F - %T - no sleep!"

Inside a crontab, that needs to be written as:

* * * * * root date "+\%F - \%T - no sleep!" >> /home/thomas/1-18-WD/ami
steeldriver
  • 136,215
  • 21
  • 243
  • 336
  • date "+%F - %T - no sleep!" >> /home/thomas/1-18-WD/ami neither date "+%F - %T - no sleep!" >> /home/thomas/1-18-WD/ami doesn't work. – ThomasHunter May 24 '21 at 21:08
  • @ThomasHunter can you be more specific? please append 2>&1 to capture any error output to your file as well – steeldriver May 24 '21 at 21:17
  • @ThomasHunter also note that the username field (root in your example) is only required in the systemwide /etc/crontab file - if you are using a user-crontab via crontab -e or sudo crontab -e it is wrong and will cause the job to fail. – steeldriver May 25 '21 at 01:00