Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

409
Vistas
Add To Crontab (if not already exists) Using Bash Script

What is the correct way for a bash script to add a job to crontab, such that

  • there will be no duplicate jobs
  • the crontab file will not be resorted
  • (optional) close to being a one-liner

Came across this solution below, but it does not affect the output of running crontab -l.

grep 'some_user python /mount/share/script.py' /etc/crontab || echo '*/1 *  *  *  * some_user python /mount/share/script.py' >> /etc/crontab

Tried converting it to affect crontab -l,

(crontab -l | grep '/mount/share/script.py') || { crontab -l; '*/1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1'; } | crontab -

but running this command gives the error:

-bash: */1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1: No such file or directory
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

but running this command gives the error:

-bash: */1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1: No such file or directory

The code:

(crontab -l | grep '/mount/share/script.py') || { crontab -l; '*/1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1'; } | crontab -

will try to execute/run the:

'*/1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1'

If and when grep failed.


Add an echo in front of it or printf, since crontab is expecting input from stdin, like what you did on your first example/code, something like:

(crontab -l | grep '/mount/share/script.py') || { crontab -l; echo '*/1 * * * * some_user python /mount/share/script.py >> /root/foo/logs/foo.cron.log 2>&1'; } | crontab -

Here is an alternative, which is a full blown script.

#!/usr/bin/env bash

cron_entry=$(crontab -l 2>&1)
is_in_cron='/mount/share/script.py'
new_cron_entry='*/1 * * * * some_user python /mount/share/script.py >> /tmp/foo/logs/foo.cron.log 2>&1'

if [[ $cron_entry != *"$is_in_cron"* ]]; then
  printf '%s\n' "$cron_entry" "$new_cron_entry" | crontab -
fi
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda