In the following crontab, add a simple job to log the top 20 processes by memory usage every hour. The job uses the top command to list processes sorted by memory usage and pipes the output to head to get the top 20 processes. The output is then appended to a file top.log. The 2>&1 redirects both standard output and standard error to the file.
We expect to see the top 20 processes by memory usage logged to top.log every hour like so:
However, the job does not run as expected. We don’t see the file top.log and it indicates that the cron is not working since just running the command on the terminal shows the output as expected.
The issue is with the % character in the command. The % character is a special character in Cron and must be escaped with a backslash (\) to be treated as a literal %.
% is a special character for crontab. From man 5 crontab:
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 a % character, will be executed by /bin/sh or by the shell specified in the SHELL variable of the cronfile. A % character in the command, unless escaped with a backslash (\), will be changed into newline characters, and all data after the first % will be sent to the command as standard input.
So you need to escape the % character.
After adding the backslash to escape the % character, the crontab works as expected.