Ubuntu: wait for network link up and execute a bash command

前端 未结 3 985
自闭症患者
自闭症患者 2021-01-16 12:28

In Ubuntu (the latest distro is fine), I want to reboot a router and inside a bash script I\'d like to have a command that waits for the network link to be up again and, whe

相关标签:
3条回答
  • 2021-01-16 13:02

    The event listener I suggested:

    inotifywait -e modify /sys/class/net/eth0/carrier; echo 'Change detected'
    

    When you plug or unplug network cable, it will trigger echo 'Change detected', of course it could trigger just about anything.

    And this will run as one off, but I take you know how to make a daemon out of it, if not it will be a good exercise to learn :)

    0 讨论(0)
  • 2021-01-16 13:11

    If you want a command to check if the link is up or down use ip :

    ip addr show eth0 | grep -Po "(?<=state ).*?(?=\s)"
    DOWN
    
    ip addr show wlan0 | grep -Po "(?<=state ).*?(?=\s)"
    UP
    
    0 讨论(0)
  • 2021-01-16 13:13

    You can check link is up/down by /sys/class/net/eth0/carrier file

    cat /sys/class/net/eth0/carrier
    

    if output is 1 then ethernet cable is plugged in and link is up.

    if output is 0 then ethernet cable is removed and link is down.

    Note:if you have interface other then eth0 then replace interface like eth2/eth3 in place of eth0

    0 讨论(0)
提交回复
热议问题