Watch for file changes in Linux I have installed Geekworm x735 on my Raspberry Pi, it uses the script below with an infinite loop to determine if the power button has been pressed. I know there are some Linux utils that watch for file changes (inotifywait, watch, fswatch to name a few), I wonder if they are more efficient than this solution or if under the hood they apply the same logic.


while [ 1 ]; do
  shutdownSignal=$(cat /sys/class/gpio/gpio$SHUTDOWN/value)
  if [ $shutdownSignal = 0 ]; then
    /bin/sleep 0.2
  else
    pulseStart=$(date +%s%N | cut -b1-13)
    while [ $shutdownSignal = 1 ]; do
      /bin/sleep 0.02
      if [ $(($(date +%s%N | cut -b1-13)-$pulseStart)) -gt $REBOOTPULSEMAXIMUM ]; then
        echo "X735 Shutting down", SHUTDOWN, ", halting Rpi ..."
        sudo poweroff
        exit
      fi
      shutdownSignal=$(cat /sys/class/gpio/gpio$SHUTDOWN/value)
    done
    if [ $(($(date +%s%N | cut -b1-13)-$pulseStart)) -gt $REBOOTPULSEMINIMUM ]; then 
      echo "X735 Rebooting", SHUTDOWN, ", recycling Rpi ..."
      sudo reboot
      exit
    fi
  fi



Thank you.
Polling like this is a very inefficient mechanism, but for pseudo-files in /sys/, you may find that the usual kernel interfaces as used by inotifywait and the like don't get notified of changes in the same way that they do for real storage-backed files.  So it may be that you need to poll, unfortunately.  But do check, for the files you care about.
There doesn't seem to be any value creating shutdownSignal to immediately use - simpler to just insert the value directly:
while [ $(&lt;/sys/class/gpio/gpio$SHUTDOWN/value) = 1 ]

sudo is intended for interactive use, and doesn't work well in scripts.  I think it's better to assume (or check) that the script is invoked with sufficient capabilities to do the work it needs to do.
Don't forget to add a shebang line (#!/bin/bash).