Question: What is the reason my cron job does not gets executed when i use percentage ‘%’ in my cron job. How to solve this issue ?
Answer:‘%’ is the new line specifier in cron command. Thus when you use % it is interpreted as a new line in the cron job. Let us see how to over come this issue, and use % in the cron job.
Problem Definition With Example: ‘%’ in the cron job ( non successful cron job )
* * * * * date +"%d" >> /tmp/non-working-ex1.txt
For testing purpose all fields in the above crontab example has * in it. This will execute the specified cronjob every minute.
To understand the crontab configuration, read our earlier article that contains 15 awesome cron job examples.
If you have access to syslog you will a similar line like the following.
Jun 20 08:31:01 ubuntu-laptop /USR/SBIN/CRON: (ramesh) CMD (date +")
In the syslog entry for this specific example the command is show only as: (date +”). Ideally this should be displayed as: date +”%d” . This indicates that the percentage is parsed as a special symbol in the cron. i.e it terminates the command exactly at the %age.
Solution With Example: Work around to use ‘%’ in the cron job.
You can solve this problem using the following two methods. This solution should solve the problem on all flavors of Unix / Linux, including Ubuntu, Debian, Fedora, RedHat, CentOS, AIX etc.,
Method 1: Escaping the percentage with \
You can escape the percentage with backslash, and make it working as a normal job.
$ crontab -l * * * * * date +"\%M" > /tmp/working-ex1.txt
Note: This ‘\’ will not be seen by date command, or any other command you invoke. The \ is to escape the special behavior of percentage in cron.
Method 2: Use Shell Script
Create a shell script with the percentage command and schedule the shell script as cron job.
$ cat /bin/date.sh date +"%d" $ crontab -l * * * * * /bin/sh /bin/date.sh > /tmp/working-ex2.txt
At the next minute you will be having the executed command output in the /tmp/working-ex2.txt
Now you will have the following line which executed the command successfully in the syslog.
Jun 20 08:36:01 ubuntu-laptop /USR/SBIN/CRON: (ramesh) CMD (/bin/sh /bin/date.sh >> /tmp/working-ex2.txt)
Note: Don’t forget to remove these testing cron entries as it will get executed every minute.
If you had any other issue with the crontab, let us know it in the comments section.
Get the Linux Sysadmin Course Now!