I need this too, just a small modification to your proposal
def_interface=$(ip route get 1.1.1.1 | head -1 | cut -d ' ' -f 5) ip addr show $def_interface | fgrep 'inet ' | awk '// {print $2}'
use fisrt command to isolate active interface