I get the following error in my syslog:
Oct 17 13:14:03 tracker cron[873]: (*system*) ERROR (Syntax error, this crontab file will be ignored)
Oct 17 13:14:03 tracker cron[873]: Error: bad minute; while reading /etc/crontab
I don’t see any bad minutes though! My crontab
file is:
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user command
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 18 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 18 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 18 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
#
asked Oct 17, 2011 at 13:54
1
Use cat -v /etc/crontab
to check for unintended control characters.
answered Oct 17, 2011 at 15:18
RedGrittyBrickRedGrittyBrick
80.6k19 gold badges132 silver badges201 bronze badges
Cron tab requires at least the first and last lines of the file not to be actual cron instructions. You can put comments instead — such as those below in a file:
# START CRON JOB LIST
* * * * * /path/to/script/script1.sh
0 3 * * 0 /path/to/script/script2.sh
5 0 * * 1 /path/to/script/script3.sh
# END CRON JOB LIST
Install it like so
sudo crontab -u user /path/to/cron/file
This should work for you.
answered Jan 28, 2016 at 21:38
1
I have faced a similar issue with this error:
crontab: installing new crontab
"/tmp/crontab.MswKCq":0: bad minute
errors in crontab file, can't install.
Do you want to retry the same edit? n
crontab: edits left in /tmp/crontab.MswKCq
Googled all round and found that this was the error due to the no space in log folder for cron i.e in /var.
Make sure to run df -h /var/
and see if there is enough space there.
answered May 25, 2020 at 19:57
2
I have same error on Ubuntu 16.04. Problem have with empty assignment to MAILTO
MAILTO=
The problem I found with the help of chkcrontab
answered Feb 9, 2017 at 14:59
orgojorgoj
1113 bronze badges
For anyone having issues on a Mac you can check your crontab for non-printing characters by typing
crontab -l | cat -e
or
sudo crontab -l | cat -e
if you have a root crontab.
answered Jun 25, 2019 at 20:06
2
solution is very simple but hidden mate.
goto
/var/spool/cron/crontabs/root
edit your crontab file via notepad++ then press CTRL+F
then goto Replace tab.
then write in.
Find with r
Replace with (this input should empty make sure no space etc)
then click replace all button.
There you go mate you issue resolve
answered Nov 7, 2022 at 12:14
This is a common error
Context
To understand this error, it’s useful to know two rules about crontab files:
- Every line in your crontab must conform with the cron specification. Other than blank lines and environment variables, every
line must be a comment (beginning with#
) or begin with a valid cron job schedule expression. - The first part of a cron job schedule expression is the minute field.
What causes this error
When cron reads each line of your crontab, if the line is not a comment it expects it to start with a valid minute expression. If for some reason it doesn’t, it will raise a Bad Minute
error.
Fixing bad minute errors
This type of error could have many causes. Here are some troubleshooting steps to identify and fix the problem.
-
The error message will commonly indicate the line number that is problematic. Look for the number after a colon, in this example it’s line 11.
"/tmp/crontab.gLfS38":11: bad minute
-
Check for unexpected line breaks in your crontab file. Sometimes you may inadvertently wrap a long line by adding a line break. Cron requires the full schedule and command on a single line.
Good:
0 0 * * * /very/long/example/command/goes/here "with several very long arguments"
Bad:
0 0 * * * /very/long/example/command/goes/here "with several very long arguments"
- If every line begins with a cron schedule, check that the first field is accurate. Here are the allowed values for the
minute
field:
Value Description 0-59 Specific Minute * Every Minute , List of Minutes, e.g. 1,3,5 — Range of Minutes, e.g 1-10 / Minute step value, e.g. 1/5 Tip:To verify and validate your cron expression use Crontab Guru, the free and simple cron expression editor from Cronitor.
-
Review any comments in your crontab file and ensure that they all start with a
#
. -
If you have verified that your cron expression is correct and you have examined each line for spurious characters or extra line breaks, it’s possible
you are dealing with a non-standard version of Cron. Review your local documentation for further guidance on crontab format. You can do this from your command line by runningman 5 crontab
Related Guides
Cronitor automatically finds and monitors cron jobs. Complete your setup in minutes.
Get Started Free
According to crontab.guru
both * * * * *
and *1 * * * *
are essentially the same thing although you may want to try the alternative just in case your system does not like one or the other.
However in your posted home.cron
the path is wrong.
This:
* * * * * /users/username/desktop/forTrump/script.sh
should be:
* * * * * /Users/username/Desktop/forTrump/script.sh
However if the script requires elevated privileges then you will need to use the root crontab and the line used is slightly different due to the addition of a user column before the command like this:
* * * * * root /Users/username/Desktop/forTrump/script.sh
To install that script as root first switch to root like this:
sudo su
followed by:
crontab home.cron
Also seeing you are on Mac OS X make sure the line in home.cron
is terminated with just n
and not r
or nr
See also: https://www.dougv.com/2006/12/fixing-a-bad-minute-error-message-when-trying-to-use-crontab-with-certain-unix-text-editors/
This problem most often occurs because you’re using a text editor, such as pico, that fakes word wrapping by adding a newline when it reaches a certain column position.
Crontab delimits jobs with line breaks (newlines). Each job occupies one line. Therefore, if crontab sees anything other than an integer in the first column of a line, it throws the “bad minute” error, since the minute argument is the first one crontab encounters.
The simple fix is to go to delete the line breaks added by pico / your *nix editor. You can most easily do that by putting your cursor on the first character of each extra line, then hit the backspace key until that line is joined back up with the previous one, and repeating the process until your entire cron command is on one line.
Содержание
- Solved: errors in crontab file, can’t install — Unix & Linux (RHEL/CentOS 7/8)
- errors in crontab file, can’t install
- Scenario 1: When number of crontab field is more than expected
- Scenario 2: If you forget to mention the Script in Crontab File
- Scenario 3: You might get «errors in crontab file can’t install bad minute»
- Scenario 4: You might get «errors in crontab file can’t install bad day-of-week»
- Scenario 5: You might get «errors in crontab file can’t install bad command»
- Scenario 6: You might get «bad day-of-month errors in crontab file can’t install»
- Bad minute crontab error
- Context
- Understand your cron jobs
- What causes this error
- Fixing bad minute errors
- Related Guides
- Подскажите, почему не отрабатывает скрипт в crontab
Solved: errors in crontab file, can’t install — Unix & Linux (RHEL/CentOS 7/8)
Table of Contents
In this article, I will explain about the «errors in crontab file, can’t install» error which I was getting while setting up the Crontab. This error is very common and can come up due to various reasons hence it is important to understand the crontab parameters. I will go through multiple scenarios in which this error could occur and how can we resolve this. But before that it is important to understand the crontab parameters through below example.
errors in crontab file, can’t install
Scenario 1: When number of crontab field is more than expected
I have been trying to set crontab from User root by running crontab -e command. After setting up the required fields I tried to save the crontab file multiple times but every time I got below error and it was not allowing me to save the file.
-e : Edits the current crontab using the editor specified by the VISUAL or EDITOR environment variables. More can be checked on crontab Man Page.
Below is what my crontab file looks like when i got the above error. If you see the below output carefully then you will see an extra star(*) field due to which above error was showing.
To resolve this issue i have removed that extra star(*) mark and then saved the file again. Then i am able to see below output which shows that crontab is successfully saved.
Scenario 2: If you forget to mention the Script in Crontab File
Another scenario could be when you forget to mention the Script in Crontab File like the one showing below. Sometimes you might forget to mention the Script file which needs to run as part of cron job and then try to save the file. In those cases also you will get the same «errors in crontab file, can’t install» error.
To fix this error you need to edit the crontab file and mention the script file name that needs to be run as part of the cron job.
Scenario 3: You might get «errors in crontab file can’t install bad minute»
I have also seen a scenario where sometimes we might add an extra line like the one mentioned below then if you try to save this crontab file you will get «errors in crontab file can’t install bad minute» error. This is because crontab expects to have a minute value mentioned at the start of every line. In this example, we have used a script called backup.sh at the start of the Line hence it will throw bad minute error.
Scenario 4: You might get «errors in crontab file can’t install bad day-of-week»
I have also seen a scenario where sometimes Linux professionals uses some value in week section which is not expected hence started getting «errors in crontab file can’t install bad day-of-week» error when try to save the file. One of the such instance I have shown below where week section expecting a value between 0 and 6 but instead 9 is mentioned which results in «bad day of the week» error.
Scenario 5: You might get «errors in crontab file can’t install bad command»
There is another common mistake I have seen Linux Professionals or Beginners often doing is that they will some unexpected command or a command which is not set in $PATH which results into «errors in crontab file can’t install bad command» error. One such instance I have shown here where jq command is not there in any of the Linux binary path hence it is not detecting this command. In these cases either you need to provide the complete path of the command or add the command path in $PATH so that system detects that command.
Scenario 6: You might get «bad day-of-month errors in crontab file can’t install»
Finally I have also seen Linux professionals or beginners doing a mistake assuming month section as days of month section and will use any value greater that 12 resulting in «bad day-of-month errors in crontab file can’t install» error. Here you need to be very careful in understanding the difference between days of the month and month of the year. Month of the year accepts value between 1 to 12 whereas days of the month accepts values between 1 to 31.
Popular Recommendations:-
Источник
Bad minute crontab error
Context
To understand this error, it’s useful to know two rules about crontab files:
- Every line in your crontab must conform with the cron specification. Other than blank lines and environment variables, every line must be a comment (beginning with # ) or begin with a valid cron job schedule expression.
- The first part of a cron job schedule expression is the minute field.
Understand your cron jobs
What causes this error
When cron reads each line of your crontab, if the line is not a comment it expects it to start with a valid minute expression. If for some reason it doesn’t, it will raise a Bad Minute error.
Fixing bad minute errors
This type of error could have many causes. Here are some troubleshooting steps to identify and fix the problem.
- The error message will commonly indicate the line number that is problematic. Look for the number after a colon, in this example it’s line 11.
- Check for unexpected line breaks in your crontab file. Sometimes you may inadvertently wrap a long line by adding a line break. Cron requires the full schedule and command on a single line.
If every line begins with a cron schedule, check that the first field is accurate. Here are the allowed values for the minute field:
Value | Description |
0-59 | Specific Minute |
* | Every Minute |
, | List of Minutes, e.g. 1,3,5 |
— | Range of Minutes, e.g 1-10 |
/ | Minute step value, e.g. 1/5 |
Tip:To verify and validate your cron expression use Crontab Guru, the free and simple cron expression editor from Cronitor.
Missing newline before EOF
No MTA installed, discarding output
Errors in crontab file, can’t install
Cronitor automatically finds and monitors cron jobs. Complete your setup in minutes.
Источник
Подскажите, почему не отрабатывает скрипт в crontab
Добрый день. Есть один скрипт recycle_clean.sh, он запускается вручную успешно и отрабатывает, но вот в /etc/crontab есть такая запись:
И из него почему-то не отрабатывает этот скрипт. Cron вроде запущен, по /etc/init.d/cron status выдает:
Стало быть крон запущен. Подскажите, почему не отрабатывает?
ls -l /root/scripts/recycle_clean.sh
head /root/scripts/recycle_clean.sh
Выложи содержимое скрипта и syslog в момент запуска кроном.
Вангую отсутствие PATH
и пустую строку в конце не забудьте.
Это группа, в ней доменные пользователи. А так, как вы предложили (* * * * *), он же не будет отрабатывать раз в сутки, или будет?
У меня нет такого лога даже: /var/log/crond.log
и пустую строку в конце не забудьте
старообрядцы в треде
Это группа, в ней доменные пользователи. А так, как вы предложили (* * * * *), он же не будет отрабатывать раз в сутки, или будет?
он будет отрабатывать 1440 раз в сутки. Каждую минуту. Ускоряет поиск ошибки в 1440 раз.
Да, таких групп не бывает в Linux’е.
У меня нет такого лога даже: /var/log/crond.log
а что, починили, да? Я не в курсе, vim подставляет самостоятельно. Но может ТС notepad.exe юзает?
Честно говоря, вообще никогда не встречал этой проблемы в реальности, и всегда думал что crontab -e сам всё валидирует и делает, хоть добавляй, хоть не добавляй
Я по мотивам какого-то треда пару лет назад тестировал это и всё работало при любом варианте
А чтобы раз в сутки нужно оставить как было:
Так как там достаточно много данных перемещает скрипт, каждую минуту не успеет.
Честно говоря, вообще никогда не встречал этой проблемы в реальности, и всегда думал что crontab -e сам всё валидирует и делает, хоть добавляй, хоть не добавляй
crontab -e вызывает EDITOR, а уж что делает $EDITOR — я не знаю. У меня это vim. А вот народ ставил mcedit, и жаловался на эту проблему.
Я по мотивам какого-то треда пару лет назад тестировал это и всё работало при любом варианте
строка должна заканчиваться n, иначе это формально не строка, а мусор. Gcc предупреждает, но компиллит. А вот как сейчас crond — я не знаю.
А чтобы раз в сутки нужно оставить как было:
там можно и это, и любое другое валидное время поставить. Сначала минуты, а потом часы. Лучше ставить на пару минут вперёд, что-бы ждать две минуты.
То есть он не отрабатывает потому что не добавлен в
а после создания такого файла и добавления в него строки, аналогичной таковой в /etc/crontab будет автоматически отрабатывать?
То есть он не отрабатывает потому что не добавлен
не. Ты даже НЕ ЗНАЕШЬ, отрабатывается он, или нет. И если нет — то почему. А в том файле это будет написано.
/var/log/crond.log а после создания такого файла
он сам создастся, с ошибками, которые нужно исправить.
и в /var/log/crond.log появилось:
bash: 59: команда не найдена
задумайся, почему именно 59?
echo нужно в начале?
эту строчку в crontab надо вставлять. В консоль вставляй БЕЗ 59 23 * * * root
Да, это была такая папка, после выполнения скрипта вручную. Я ее удалил и все запустил заново, в логе пусто после этого.
Но все равно он не отрабатывал, так как папка должна создаваться каждый день, а они не создавались. Вот только сегодня вручную запустил — тогда создались.
PATH проверил, все вроде ок в ней.
Спасибо! Она мне не помешает! =) Показал другому одмину — говорит что сам крон не работает, а crontab в порядке. Но вроде показывает:
mv: невозможно переместить «/var/share/data_drive/Disk_S/.recycled/current» в «/var/share/data_drive/Disk_S/.recycled/2014-03-05/current»: Кат$
видимо «каталог существует»
mkdir: невозможно создать каталог «/var/share/data_drive/Disk_S/.recycled/current»: Файл существует
надо проверить, потом создавать
[ -d /var/share/data_drive/Disk_S/.recycled/current ] || mkdir /var/share/data_drive/Disk_S/.recycled/current
у вас в самом скрипте ошибки.
Пусть уволится, он не админ.
Да, это после того как я вручную запустил его (скрипт), каталог создался, и при последующем запуске тоже вручную выдалась такая ошибка, так как каталог был. Я его удалил. Но кронтаб все равно не работает, не понимаю почему.
У нас просто все неспешно. =)
Сейчас содержимое /etc/crontab такое:
Но кронтаб все равно не работает, не понимаю почему.
1. исправьте ошибки в скрипте. Вот что вы мне моск полоскаете? У меня сын первоклашка, у него есть работа над ошибками. У вас какая-то альтернативная школа?
2. заведомо рабочий скрипт пропишите в crontab. Потом читайте логи.
Checking periodic command scheduler. done (running).
и что? Да, работает чего-то. У меня куча таких шедулеров. Тоже работают. Что дальше?
Да вот даже простой скрипт
* * * * * root echo ‘Время: ‘ ; date
КУДА он должен его «выполнять»? Откуда он знает, что вы эмулятор терминала где-то внутри Xorg’а запустили?
Команда выполняется, а результата ты тупо НЕ ВИДИШЬ.
SHELL=/bin/bash же указан
блжад. Это то, ЧТО выполняет. А КУДА?
Обычно по дефолту оно в почту срёт. А у тебя MAILTO=. Что значит — в никуда.
Первый раз вижу, чтобы человек «почти осилил crontab», но в тоже время демонстрировал полное непонимание основ.
А emulek должен получать молоко за вредность.
Вот попробовал на машине с точно таким же шестым дебианом —
И файл создался. А на моем злосчастном серваке — тишина при точно такой же строке.
Я не очень линуксоид по всяким серверным штукам, только как пользователь — ставлю убунты и переустанавливаю убунты.
А emulek’у я очень благодарен.
Первый раз вижу, чтобы человек «почти осилил crontab», но в тоже время демонстрировал полное непонимание основ.
Увы. С тех пор, как изобрели гугл, это обычная ситуация.
А на моем злосчастном серваке — тишина при точно такой же строке.
дык сделай логгирование, как я выше писал. Должно работать.
Да, куда ты прописываешь-то? И как?
Я просто в /etc/crontab прописал ниже под всем, ну команду touch на другой машине с аналогичным дебианом. А вот на этом серваке — тоже добавил. И не отрабатывает. Крон вроде везде одинаковый. Может его переставить? Просто не хотелось бы перезапускать этот сервак. Но просто перезапуск крона не помогает.
думаешь мне интересно, через какую жопу ты делаешь? Нет.
Просто скрипт же отрабатывает если вручную его запускать. Значит не в нем проблема.
Во-первых, если скрипт при повторном запуске без изменения входных данных может обломаться, то это плохой скрипт: http://ru.wikipedia.org/wiki/Идемпотентность
Во-вторых, настройте почтовую подсистему (достаточно взять какой-нибудь nullmailer, чтобы слал через smtp) и настройте перенаправление почты root-а к себе на ящик (ну, или локально складывать, если на машине нет интернета/доступа к какому-нибудь smtp-серверу). Это будет полезно не только для отладки cron, но и для получения информации по многим системным событиям (smartd руту пишет, например, когда на дисках происходит что-то нехорошее).
В-третьих, чтобы закончить бессмысленные аргументы на тему того, что «cron не работает», посмотрите /var/log/syslog. Там будут строчки типа:
Найдите строчки, которые соответствуют запуску задания с вашим скриптом (они там будут, даже если скрипт обломается).
Источник
In this article, I will explain about the «errors in crontab file, can’t install» error which I was getting while setting up the Crontab. This error is very common and can come up due to various reasons hence it is important to understand the crontab parameters. I will go through multiple scenarios in which this error could occur and how can we resolve this. But before that it is important to understand the crontab parameters through below example.
* * * * * /home/centos/example.sh
| | | | | |
| | | | | Command or Script to execute
| | | | |
| | | | Day of week(0-6)
| | | |
| | | Month(1-12)
| | |
| | Day of Month(1-31)
| |
| Hour(0-23)
|
Min(0-59)
Also Read: 11 Unix/Linux chmod Command examples to Change File Permissions
Scenario 1: When number of crontab field is more than expected
I have been trying to set crontab from User root by running crontab -e
command. After setting up the required fields I tried to save the crontab file multiple times but every time I got below error and it was not allowing me to save the file.
[root@localhost ~]# crontab -e no crontab for root - using an empty one crontab: installing new crontab "/tmp/crontab.gsQNhu":1: bad command errors in crontab file, can't install. Do you want to retry the same edit? y crontab: installing new crontab "/tmp/crontab.gsQNhu":1: bad command errors in crontab file, can't install. Do you want to retry the same edit? y
-e : Edits the current crontab using the editor specified by the VISUAL or EDITOR environment variables. More can be checked on crontab Man Page.
Below is what my crontab file looks like when i got the above error. If you see the below output carefully then you will see an extra star(*)
field due to which above error was showing.
0 3 * * * * /home/centos/example.sh
To resolve this issue i have removed that extra star(*)
mark and then saved the file again. Then i am able to see below output which shows that crontab is successfully saved.
crontab: installing new crontab
Scenario 2: If you forget to mention the Script in Crontab File
Another scenario could be when you forget to mention the Script in Crontab File like the one showing below. Sometimes you might forget to mention the Script file which needs to run as part of cron job and then try to save the file. In those cases also you will get the same "errors in crontab file, can't install"
error.
0 2 * * *
To fix this error you need to edit the crontab file and mention the script file name that needs to be run as part of the cron job.
Scenario 3: You might get «errors in crontab file can’t install bad minute»
I have also seen a scenario where sometimes we might add an extra line like the one mentioned below then if you try to save this crontab file you will get "errors in crontab file can't install bad minute"
error. This is because crontab expects to have a minute value mentioned at the start of every line. In this example, we have used a script called backup.sh
at the start of the Line hence it will throw bad minute error.
0 3 * * * /home/centos/example.sh backup.sh
Scenario 4: You might get «errors in crontab file can’t install bad day-of-week»
I have also seen a scenario where sometimes Linux professionals uses some value in week section which is not expected hence started getting "errors in crontab file can't install bad day-of-week"
error when try to save the file. One of the such instance I have shown below where week section expecting a value between 0 and 6 but instead 9 is mentioned which results in "bad day of the week"
error.
* 4 0 * 9 /home/centos/example.sh
Scenario 5: You might get «errors in crontab file can’t install bad command»
There is another common mistake I have seen Linux Professionals or Beginners often doing is that they will some unexpected command or a command which is not set in $PATH
which results into "errors in crontab file can't install bad command"
error. One such instance I have shown here where jq
command is not there in any of the Linux binary path hence it is not detecting this command. In these cases either you need to provide the complete path of the command or add the command path in $PATH
so that system detects that command.
0/10 * * * * jq
Scenario 6: You might get «bad day-of-month errors in crontab file can’t install»
Finally I have also seen Linux professionals or beginners doing a mistake assuming month section as days of month section and will use any value greater that 12 resulting in "bad day-of-month errors in crontab file can't install"
error. Here you need to be very careful in understanding the difference between days of the month and month of the year. Month of the year accepts value between 1 to 12 whereas days of the month accepts values between 1 to 31.
* * * 15 * /home/centos/example.sh
Popular Recommendations:-
Learn HTML Image Maps(v5) with Best Examples
Easy Steps to Install GCC(C and C++ Compiler) on CentOS 7
C# data types with Best Examples (.NET v4.7)
How to Transfer Files to an AWS EC2 Instance Using WinSCP in 3 Easy Steps
Learn HTML Tables(v5) with Best Examples
How to Install PHP on RedHat/CentOS 7 with Easy Steps
How to Install Ruby on Ubuntu 18.04 with Easy Steps
Better Stack Team
Updated on January 9, 2023
Cause of the error
Cron reads every line of the crontab. If the line is not a comment or an
environmental variable, cron expects a correct and valid minute expression of
the cronjob. If there is an invalid minute expression (e.g. a typo), cron will
throw a Bad minute error.
Solution
Troubleshooting
- The error message includes a specific line number. Look at the line and
look for syntax errors and typos.
"/tmp/crontab.gLfS38":4: bad minute
#error on line 4
- Check for unexpected line breaks. Check the example of an unexpected line
break bellow:
0 0 * * *
/command/to/execute
Make sure there is one cronjob per line. One cronjob should not be defined on
multiple lines.
- Make sure all comments start with # and are on separate lines.
- Check if time schedule corresponds with the syntax rules as shown bellow
Crontab syntax
Crontabs have simple, but strict syntax rules. Every crontab file has to:
- Start whit a correct cron schedule (can be an environmental variable) or
comment on every line - Contain a username for each cron job
- Contain valid and executable shell expression
- End with a newline
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | | .---- username
# | | | | | |
# * * * * * user command to be executed
* * * * * root echo 'Hello world!'
🔭 Want to get alerted when your Cron doesn’t run correctly?
Go to Better Uptime and start monitoring them in 5 minutes.
Got an article suggestion?
Let us know
Explore more
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.