I would like to catch docker events and do something if something is happend. There are lots of ways to "get/print events":
# With curl
curl --unix-socket /var/run/docker.sock http:/v1.40/events
# With nc
echo -e "GET /events HTTP/1.0\r\n" | nc -U /var/run/docker.sock
But is there any way to listen continously and handle each row/event? Eg:
while EVENT ?magic?; do
ACTION=$(echo $EVENT | jq .Action )
if [ $ACTION -eq "start" ]; then ....; fi
done
Solution
After @Adiii answer, a short solution:
#!/bin/bash
function handle {
# Check the line is a JSON line:
if [[ ${1:0:1} == "{" ]]; then
# ... You can do here anything ...
# Print: "LOG $line", "LOG" is green
echo -e "\033[32;1mLOG\033[0m $line"
fi
}
echo -e "GET /events HTTP/1.0\r\n" | nc -U /var/run/docker.sock | while read line; do handle $line; done;