Shell – How wait for eth0 interface before running “ip link”, “ip addr” and “ip route” commands

linuxnetworkingshell-scriptsynology

I have the following script that I need to run on my Synology NAS at boot-up. The Synology NAS has built-in scheduled tasks with the ability to trigger tasks at boot-up.

The script I need to run is this:

#!/bin/sh

ip link add macvlan0 link eth0 type macvlan mode bridge
ip addr add 192.168.0.240/32 dev macvlan0
ip link set macvlan0 up
ip route add 192.168.0.240/28 dev macvlan0

However, this does not work, the task seems to trigger to soon when the eth0 interface is not yet ready to accept these commands.

Placing a sleep 60 before all ip * commands, solves the issue. But it doesn't feel right to wait an arbitrary amount of seconds before doing my thing.

Given my requirements above, what's the best method to wait for the eth0 interface to be available so that I can execute ip * commands?

Best Answer

Check the status of eth0 from /sys/class/net/eth0/operstate and wait until the network interface to be up:

while ! [ "$(cat /sys/class/net/eth0/operstate)" = "up" ] 
do
    echo  "waiting for eth0 to be up"
    sleep 2
done

ip link add macvlan0 link eth0 type macvlan mode bridge
ip addr add 192.168.0.240/32 dev macvlan0
ip link set macvlan0 up
ip route add 192.168.0.240/28 dev macvlan0
Related Question