Writing a specific format of time in a text file every minute using Cron [duplicate]

I'm rather new to Linux. I recently wanted to learn how to work with Cron. So I wrote the following line to crontab file and it worked:

* * * * * date >> //home/os/system-date.txt

This line will append the current date and time in system-date.txt every minute.

When I run the following command in terminal, time is printed in a specific format:

date +"%H-%M-%S"

For instance, 23-59-59 is printed.

But when I want to do this with Cron, nothing is written in the txt file. To be specific, when I write the following line in crontab

* * * * * date +"%H-%M-%S" >> //home/os/system-date.txt

nothing happens. I wonder why.


You should escape the percent (%) signs in your crontab entries with a backslash (\) like this:

* * * * * date +"\%H-\%M-\%S" >>/home/os/system-date.txt 2>>/home/os/system-date.err

Percent signs have a special meaning in crontab entries: They are interpreted as newline characters. Please, see the man page for crontab(5):

The "sixth" field (the rest of the line) specifies the command to be run. The entire command portion of the line, up to a newline or % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the crontab file. Percent-signs (%) in the command, unless escaped with backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input. There is no way to split a single command line onto multiple lines, like the shell's trailing "\".

Also, note that the command in a crontab entry will not be executed by /bin/bash normally. So, it is always a good practice to create a Bash script and call that Bash script from crontab. Another point to note is that the PATH environment variable is much simpler in a crontab executed command (or script), so it is again a good practice to use full path names for commands executed in a script which is written to be called by crontab.