Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

411
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda