Why Cron Does Not Run a Task That Works in the Terminal
Check the user, schedule, and Cron environment without manually re-running a potentially dangerous task or modifying crontab.

In this article
Скрипт успешно выполняется вручную, но не даёт результата по расписанию. В терминале он получает окружение пользователя, рабочий каталог и интерактивные настройки. У cron условия другие. Диагностика начинается с точной записи задания и способа его исполнения, а не с добавления ещё одной копии в расписание.
Посмотрите таблицу текущего пользователя
Пример рассчитан на обычную реализацию cron в Debian или Ubuntu. Для просмотра используется:
crontab -l
Команда ничего не редактирует. Сообщение об отсутствии таблицы у текущего пользователя не означает, что на сервере вообще нет задания: оно может принадлежать другому аккаунту, находиться в системном расписании или запускаться таймером systemd.
Не используйте команды удаления или установки таблицы при первоначальном разборе. Важно сначала найти существующую запись и избежать дублирования, особенно если задача отправляет письма, создаёт документы или передаёт заказы.
Проверьте формат записи
В пользовательской таблице после полей расписания идёт команда. У системных таблиц есть дополнительное поле пользователя. Перенос строки между этими форматами без адаптации приводит к неожиданной интерпретации.
Проверьте минуту, час, день месяца, месяц и день недели. Условия дня месяца и дня недели имеют особенности совместной обработки в распространённых реализациях cron. Если расписание сложное, сверяйте его именно с документацией установленной версии, а не с ожиданием по внешнему виду строки.
Сравните окружение
Уточните полный путь к интерпретатору и программе, переменные, от которых зависит скрипт, и рабочий каталог. Команда, найденная в интерактивном терминале через пользовательский PATH, может отсутствовать в окружении задания.
Пример: скрипт открывает файл по относительному пути. В ручном тесте вы заранее перешли в каталог проекта, а cron запускает его из другого места. В этой ситуации проблема не в расписании. Нужно сделать рабочий каталог или пути явными в согласованной конфигурации задания.
Найдите вывод и факт запуска
Проверьте, куда направлены стандартный вывод и ошибки. Если они нигде не сохраняются и доставка локальной почты не настроена, важное сообщение может остаться незамеченным. Наличие строки запуска в системном журнале подтверждает запуск команды, но не успешный результат приложения.
В Debian-подобной системе журнал службы cron можно просмотреть за короткий период, если он поступает в journal:
journalctl -u cron.service --since '-1 hour' --no-pager
Имя службы и способ журналирования зависят от системы. Пустой вывод требует проверки этих условий, а не вывода о том, что планировщик ничего не делал.
Не запускайте задачу повторно вслепую
Если предыдущий экземпляр ещё работает, повтор может создать конкуренцию или дубли. Сначала выясните, предусмотрена ли защита от параллельного запуска и безопасно ли повторение операции. Для проверки можно подготовить отдельный безвредный сценарий в тестовой среде, но не заменять им доказательство исправности рабочего задания.
Сохраните пользователя, расписание, путь программы, окружение и результат последнего запуска. После точечного исправления дождитесь согласованного срабатывания и проверьте конечный результат. Успешный ручной запуск — полезная исходная точка, но только выполнение в условиях планировщика подтверждает решение проблемы.
The script runs successfully when executed manually but yields no result on schedule. In the terminal, it receives the user's environment, working directory, and interactive settings. Cron operates under different conditions. Diagnosis begins by precisely recording the task and its execution method, not by adding another copy to the schedule.
View the current user's table
The example assumes a standard Cron implementation in Debian or Ubuntu. To view it, use:
crontab -l
The command does not edit anything. A message indicating the absence of a table for the current user does not mean the server has no tasks at all: the task may belong to another account, reside in the system schedule, or be triggered by a systemd timer.
Do not use commands to delete or install a table during initial analysis. It is crucial to first locate the existing entry and avoid duplication, especially if the task sends emails, generates documents, or processes orders.
Check the record format
In a custom table, the command follows the schedule fields. System tables have an additional user field. Moving between these formats without adaptation leads to unexpected interpretation.
Check the minute, hour, day of the month, month, and day of the week. The day of the month and day of the week conditions have specific handling quirks in common cron implementations. If the schedule is complex, verify it against the documentation for the installed version, not based on the visual appearance of the string.
Compare the environment
Verify the full path to the interpreter and program, the variables the script depends on, and the working directory. A command found in an interactive terminal via the user's PATH may be missing in the job environment.
Example: a script opens a file using a relative path. In a manual test, you switched to the project directory beforehand, but cron launches it from a different location. In this situation, the issue is not with the schedule. You must make the working directory or paths explicit in a consistent job configuration.
Find the output and the launch fact
Check where standard output and errors are directed. If they are not saved anywhere and local mail delivery is not configured, an important message may go unnoticed. The presence of a launch entry in the system log confirms the command started, but not that the application succeeded.
In a Debian-based system, the cron service log can be viewed for a short period if it is sent to the journal:
journalctl -u cron.service --since '-1 hour' --no-pager
The service name and logging method depend on the system. Empty output requires checking these conditions, not concluding that the scheduler did nothing.
Do not blindly re-run a task
If the previous instance is still running, a re-run can cause contention or duplication. First, determine whether protection against parallel execution is in place and whether repeating the operation is safe. To verify, you can prepare a separate harmless script in a test environment, but do not use it as a substitute for proof that the production task is working correctly.
Save the user, schedule, program path, environment, and the result of the last run. After a targeted fix, wait for the scheduled execution to occur and verify the final result. A successful manual run is a useful starting point, but only execution under the scheduler confirms that the issue is resolved.

Discussion0
Share your experience and ask questions. Comments without links appear after editorial review.
No comments yet. Start the discussion.