1

My end goal is to create a script that runs on startup that turns off wifi when an Ethernet cable is plugged in, and vice-versa. This is the script I've created so far:

#!/bin/bash
File=/sys/class/net/eth0/carrier
function toggle {
        if grep -q 1 "$File"; then
                echo "Yes"
        else
                echo "No"
        fi
}

toggle # Once on startup
while inotifywait -q $File; do
        toggle
done

I've confirmed that plugging in and unplugging the Ethernet cable does change /sys/class/net/eth0/carrier, but for some reason, absolutely nothing happens when it's updated. I tested if the command was detecting changes at all by changing File to be a temporary file in my home directory called "test.txt". Whenever I accessed the file, changed its contents etc., the script continued as expected. I tried overwriting the file by doing echo '1' > test.txt, which worked. Deleting the file resulted in an error and the script terminating, but at least it registered a response.

I could just set the script to execute every second, but I'd like to avoid that if possible.

1 Answers1

0

According to this and this, inotify may not work on /sys files.

An alternative is to use ip monitor and check for state UP or state DOWN strings:

ip monitor link dev eth0 | awk '/state DOWN/{print "No"} /state UP/{print "Yes"}'
oliv
  • 12,690
  • 25
  • 45
  • Thanks for the insight. I tried running that command you gave me, and nothing happened when I plugged/unplugged my ethernet cable. I tried changing both occurrences of "print" to "echo", but still nothing. Tried running as sudo; still nothing. –  Sep 06 '19 at 10:21