How do I execute a script after DHCP assigns an IP address on start up?

I have written a shell script that sends my current IP to a google drive folder to aid in automating logging into a raspberry PI. Another script on my laptop retrieves the IP and logs in. The script works fine when I run it from the command line but I am having trouble getting it to run on start up after the IP is assigned.

I have tried crontab but the script runs before the IP is assigned. I do not wish to set a timer or uses a while loop to wait for an IP, that doesn't sound very efficient. I am trying to execute my script during the start up process but after DHCP runs. I tried adding the path to upstart in the allinterfaceup() function but that did not work either. Any help would be appreciated.

Raspberry PI 3, Ubuntu Mate 16.04 LTS

script:

#!/bin/sh

#if ([ $reason = "BOUND" ] || [ $reason = "RENEW" ] )
#then

        echo `hostname -I | cut -d' ' -f1 ` > ~/ipAddr/ip.txt

        rclone copy ~/ipAddr/ip.txt remote:pi 
#fi

Solution 1:

Hooks


There is an array of possibilities how to do this.

If you want to execute your script " after DHCP runs " then hooks are the right thing for you !

dhclient will execute everything in the directory /etc/dhcp/dhclient-exit-hooks.d/ after it exits.*

Its good practice to link your script to the directory, rather than place it there - but both works.

ln -s /path/to/your/script  /etc/dhcp/dhclient-exit-hooks.d/name_of_your_script

(*) However, dhclient doesn't "exit" per se, but rather continues to run and executes ("sources") this directory every-time it does something for a reason.

So, to prohibit your script from being executed numerous times, I suggest you wrap it with an "if statement" to execute it only if the IP address is bound or renewed like this:

if ([ $reason = "BOUND" ] || [ $reason = "RENEW" ])
then

# your script commands here

fi