3

I have a bash script in crontab that runs @reboot:

The script itself contains a wget command to pull and download a file from the internet

When I run my script after signing in and opening the terminal it works and saves the files properly(html, png). But when I reboot my system it saves runs and saves as plain text files with no content.


Solved

--> I used the sleep function in crontab and it works!!!

New to linux and code, so thanks for all the feedback! I'm going to explore the /etc/network/if-up.d/ options as well.

  • 4
    When your script runs, is the network accessible yet? – Nick ODell Aug 1 '18 at 3:24
  • Please post the entry from crontab as well as some portion of the script so we can assist further. – slm Aug 1 '18 at 11:08
1

The issue is almost certainly that your @reboot cron job has started before your network interfaces have come up. This is, in general, a well-documented shortcoming of cron. It doesn't mean the @reboot facility is useless, it just means you need to understand how it works, and how to work around it when it fails - as it has in your case (probably :).

There are at least 2 ways to do this:

  1. use sleep in your @reboot job to give the network more time to get up. Your crontab entry will look something like this: :

@reboot sleep 10; /your/bash/script/as-it-is-now

I suggested the value of 10 here to give the interface 10 seconds to come up; YMMV, so experiment with different values.

  1. following up on @confetti 's suggestion (and with thanks to @Celada), put your script in /etc/network/if-up.d. Following is a prototype that may be useful. Note that it only runs the first time your system comes up (like @reboot, and NOT each time the network interface is brought up):

#!/bin/sh

NWKSTATUS=/var/run/the-network-is-up

# note that /var/run is a temp fs, and so a system shutdown
# will effectively erase our flag file, 'the-network-is-up'

case "$IFACE" in
lo)
# Exclude the loopback interface; we won't consider it
# as it's not a true interface. We set the flag only
# when a true network interface comes up
exit 0
;;
*)
;; esac

# if the flag file exists, we're done here
# otherwise, we'll create it

if [ -e $NWKSTATUS ]; then exit 0
else
touch $NWKSTATUS
fi

# add your script here...

So - put all of the above into a file (e.g. setnwkstatus.sh), then save it in the folder /etc/network/if-up.d/ and make it executable (i.e. sudo chmod /etc/network/if-up.d/setnwkstatus.sh )

1

Most likely the issue is that the network interface isn't up at the time cron tries to run your script.

You could make the script run after the network interface is up.

Put your script in /etc/network/if-up.d and set chmod +x so it can be executed. Everytime a network interface comes up, every script in there will be executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.