right format of date command in crontab

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.

0

2 Answers

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.

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
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like