etherswitch.sh 663 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/bin/env bash
  2. switch_state=0
  3. function check_fn {
  4. type $1 &> /dev/null || {
  5. echo "$1 is undefined"
  6. exit 1
  7. }
  8. }
  9. source ~/.etherswitch
  10. if [ -z "$device" ]
  11. then
  12. echo "device is not set"
  13. exit 1
  14. fi
  15. # check if $device is a network device
  16. ip link show $device > /dev/null
  17. if [ $? -eq 1 ]; then exit 1; fi
  18. check_fn "on_switch_close"
  19. check_fn "on_switch_open"
  20. while :
  21. do
  22. ip link show $device | grep -q "LOWER_UP"
  23. if [ $? -eq 1 ]
  24. then
  25. if [ $switch_state -eq 1 ]
  26. then
  27. switch_state=0
  28. on_switch_open
  29. fi
  30. else
  31. if [ $switch_state -eq 0 ]
  32. then
  33. switch_state=1
  34. on_switch_close
  35. fi
  36. fi
  37. sleep 0.3
  38. done