You can use the pre-up
option to run check if the interface has link (i.e. a cable is connected) and return a non-zero exit code otherwise. That will cause ifup
to abort instead of trying to bring up the interface.
From man 5 interfaces
:
pre-up command
Run command
before bringing the interface up. If this command fails then ifup
aborts, refraining from marking the interface as configured, prints an error message, and exits with status 0. This behavior may change in the future.
Something like this should work:
allow-hotplug eth0
iface eth0 inet dhcp
pre-up ip link set eth0 up && sleep 1
pre-up [ $(cat /sys/class/net/eth0/carrier) -eq 1 ]
The first command tries to bring up the interface. The second command checks if the interface has link. If either of the command fails (e.g. because no ethernet cable was plugged in), the interface is left unconfigured.