How to detect a mobs health, on Java 1.17

You can get the health of any entity by using the /data command. Try it on yourself:

data get entity @s Health

If you are at full health, you should see "ginkgo has the following entity data: 20.0f". If you have taken some damage, you might see "ginkgo has the following entity data: 18.44835f".

This alone is already enough to detect health, for example—you can detect when your player is at full health:

execute if entity @s[nbt={Health:20.0f}] run say I am fully healed!

Or your player is at exactly half health:

execute if entity @s[nbt={Health:10.0f}] run say I am at exactly half health. Not a fraction above or below!

The only issue is that in this format, it is difficult (if not impossible) to detect if an entity is within a certain Health range. To test for a range, we need to convert the Health into a format that can be tested easily: scores.

Using the execute store result score command, we can store the Health of an entity onto a scoreboard. To do so, we will use a dummy scoreboard.

scoreboard objectives add Health dummy

Now, we can store our Health onto the dummy scoreboard:

execute store result score @s Health run data get entity @s Health

If you use /scoreboard objectives setdisplay sidebar, you can view your Health on the sidebar. If you take some damage, you might notice that your Health is always listed as a whole number instead of a decimal like before (18.44835f). This is because scoreboard values are stored as integers, which can only be a whole number. It will truncate any decimal values (? i think). This will not really matter for your purposes, anyways.

Now that your Health is stored in scoreboard form, we can easily test for a range:

execute if score @s Health matches ..10 run say I am under half health!