-1

I am trying to automate a bash script in Ubuntu. The script pings a server and then runs a python script if the packet is not received. The python script sends me a a notification when the ping is not returned. The script works when I run it manually, but it is not working when I schedule a cron job.

The bash script is named ping.sh.

#!/bin/bash


pingString=$(ping -c 1  google.com) # google is just and example, for my script I am using a server that intentionally does not return the packet.
msgRecieved="1 received, 0% packet loss"
msgLost="0 received, 100% packet loss"


if `echo ${pingString} | grep "${msgLost}" 1>/dev/null 2>&1`
then
  python3 ping.py
fi

This is how I setup the cron job: crontab -u username -e

* * * * * /bin/sh /home/username/Documents/ping.sh

I am confused because I set other dummy cron job for testing and it works fine. Example below:

* * * * * /bin/sh /home/username/Documents/test.sh

test.sh

#! /bin/bash

touch /home/username/Documents/ping_server/text.txt

The text.txt file is successfully created every minute.

Redz
  • 324
  • 1
  • 4
  • 16
  • Look for cron script failure here in this forum. – Jetchisel Sep 05 '22 at 01:15
  • Some `ping` implementation outputs a string such as "0 **packets** received, 100% packet loss". Please check what kind of string is given by your `ping`. – tshiono Sep 05 '22 at 01:44
  • Apply standard troubleshooting steps [in this question](https://stackoverflow.com/questions/22743548/cronjob-not-running/22744360#22744360) (especially checking `PATH` and capturing error output). Side notes: those backticks in the `if ...` line should not be there (they make it try to execute the output of the pipeline as a command... but there is no output because it's redirected), and you should use `grep -q` instead of redirecting its output. Also, sometimes `ping` will output an error message instead of any actual result (e.g. if it can't resolve the domain name). – Gordon Davisson Sep 05 '22 at 01:46
  • Better use exit code of ping command instead of grepping its output. Like so: `ping -c 1 google.com &> /dev/null; err=$?` than `if ((err>0)); than ... fi` – Ivan Sep 05 '22 at 05:44

1 Answers1

0

Thanks for the suggestions. My problem was solved by

  1. adding full path of the python script "ping.py" in the bash script
  2. adding environment variables to crontab

I didn't know environment variables set in .bashrc are not loaded when running cron.

In Ubuntu it is possible to declare env variables before the jobs scheduled just like you would in bash.rc:

crontab -u username -e

ENV_VAR1=variable1

* * * * * /bin/sh /home/username/Documents/ping.sh