The following works for me:
STYLUS_ID=11 # replace with ID or name of your stylus
TOUCH_ID=9 # replace with ID or name of your touch screen
xinput test -proximity "$STYLUS_ID" |
while read line; do
if [[ $line == *out* ]]; then
xinput enable "$TOUCH_ID"
else
xinput disable "$TOUCH_ID"
fi
done
Instead of polling the state of the stylus, it relies on the option `test` of `xinput`, which enters an endless loop displaying `proximity` events for the device. From `xinput`'s man page:
test [-proximity] device
Register all extended events from device and enter an endless loop
displaying events received. If the -proximity is given, ProximityIn
and ProximityOut are registered.