jq

Subscribing to a Window event with Sway


I'm using sway and would like to perform some action in bash, when a certain window is created. Right now this is what I have:

swaymsg -mt subscribe '["window"]' | 
jq 'select(.change == "new") | 
select(.container.window_properties.class == "frontend")' |
while read -r _; do
    echo WORKS          
done 

So far, if I remove the while loop, I get the text I expect printed out to the terminal so I think my jq filter works. But I'm stumped why "WORKS" doesn't get printed. I assume I'm doing something silly that I didn't realize. Any help is appreciated. :)


Solution

  • I ran into this same issue and found that I had to adjust stdin buffering (https://linux.die.net/man/1/stdbuf). For example

    swaymsg -m -t subscribe '["window"]' \
      | stdbuf -o L jq -c 'select(.change == "focus")' \
      | while read -r string; do
        echo $string | jq
    done
    

    Key things here are stdbuf -o L , which makes the following jq command's output line buffered, and jq -c which makes jq output an object all onto one line. With this, the read command picks up the entire object into $string, which can be further manipulated in later steps.