Updated:

Deal two hearts of damage

VersionCommand
Java 1.19.4 and later/damage @p 4
Bedrock Edition/damage @p 4

The number is health points: 1 is half a heart and 2 is one heart. Players have 20 health (10 hearts), so 4 removes two hearts. Armor reduces the damage.

Choose a damage type

VersionMagic damage that ignores armor
Java/damage @p 4 minecraft:magic
Bedrock/damage @p 4 magic

The type decides whether armor and enchantments reduce the damage. magic ignores armor, so it always removes the exact amount. Other types include fall (reduced by Feather Falling) and lava.

Set the attacker

VersionCommand
Java/damage @p 6 minecraft:mob_attack by @e[type=minecraft:zombie,limit=1,sort=nearest]
Bedrock/damage @p 6 entity_attack entity @e[type=zombie,c=1]

With an attacker, the death message names that mob. Between mobs, the damaged mob will target the attacker.

Common damage types

Java typeBedrock causeNotes
minecraft:fallfallFeather Falling and Protection reduce it.
minecraft:in_fire, minecraft:lavafire, lavaFire Protection reduces it; Fire Resistance blocks it.
minecraft:explosionentity_explosionBlast Protection reduces it.
minecraft:magicmagicIgnores armor; good for exact amounts.
minecraft:witherwitherShows the wither death message.
minecraft:drown, minecraft:starvedrowning, starveUseful for themed death messages.

The type mostly changes which enchantments help and which death message appears. Java type IDs are lowercase with underscores; Bedrock uses its own cause names, so the two lists do not match one to one.

Damage from a position (Java)

/damage @p 6 minecraft:explosion at ~ ~ ~5

at sets where the damage comes from, which decides the knockback direction. You can use either at or by, not both.

For projectiles, by is the direct source and from is who caused it. This makes the nearest zombie take arrow damage credited to you:

/damage @e[type=minecraft:zombie,limit=1,sort=nearest] 5 minecraft:arrow by @s from @s

A damage floor trap

Put this in a repeating, always active command block. Anyone standing on a magma block loses one heart:

/execute as @a at @s if block ~ ~-1 ~ minecraft:magma_block run damage @s 2 minecraft:magic

It runs every tick, but players are invulnerable for half a second after each hit, so the real rate is about two hits per second. Change the selector to @a[tag=!builder] to keep tagged builders safe in Survival.

/damage, /kill or instant damage?

GoalUse
Remove an exact amount/damage
Always kill/kill
Java 1.19.3 and earlier/effect give @p minecraft:instant_damage 1 0 (about 3 hearts at level I)

Common problems

Check your command

The Command Error Doctor checks common syntax mistakes in your browser.