Monday, April 29, 2024
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 1559  / 1 Year ago, thu, december 8, 2022, 11:52:37

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.


More From » command-line

 Answers
1

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.


[#967] Saturday, December 10, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
altybol

Total Points: 364
Total Questions: 138
Total Answers: 121

Location: France
Member since Thu, May 6, 2021
3 Years ago
altybol questions
Sat, Jul 24, 21, 03:56, 3 Years ago
Sun, Jul 10, 22, 22:37, 2 Years ago
Wed, Dec 8, 21, 20:47, 2 Years ago
;