← All Courses

Minecraft Coding: Command Your World

Free   6 lessons

Lesson 5: The /execute Command — Making Commands Smart

The /execute Command — Making Commands Smart

So far, commands just do things when you type them. The /execute command lets you add conditions — making commands run only when certain things are true. This is the closest Minecraft commands get to real programming logic.

The Concept: Conditional Execution

In real code you write things like:

if (playerHealth < 5) {
    givePlayer(healthPotion);
}

The /execute command does the same thing in Minecraft:

/execute if entity @p[distance=..5] run say Someone is nearby!

The Basic Structure

/execute [conditions] run [command]

The conditions tell Minecraft when to run the command. The run keyword starts the actual command to execute.

Running a Command As Another Entity

/execute as @e[type=minecraft:zombie] run say Brains!

Every zombie in the world says "Brains!" This runs the say command as each zombie.

Running a Command At a Location

/execute at @p run summon minecraft:lightning_bolt ~ ~ ~

Spawns lightning at the nearest player's location. The at @p shifts the execution position to the player, so ~ ~ ~ means the player's position.

Conditional: if entity

/execute if entity @p[distance=..10] run say A player is within 10 blocks!

Only runs if a player is within 10 blocks. The distance=..10 means "distance less than or equal to 10."

Conditional: if block

/execute if block ~ ~-1 ~ minecraft:grass_block run say You are standing on grass!

Checks the block directly below the execution position. ~-1 on Y means one block down.

Conditional: unless

/execute unless entity @p[distance=..20] run say Nobody is nearby.

unless is the opposite of if — runs when the condition is false.

Chaining Conditions

You can chain multiple conditions:

/execute as @a if block ~ ~-1 ~ minecraft:lava run effect give @s minecraft:fire_resistance 3 0

For every player standing on lava, give them fire resistance for 3 seconds. This is a real anti-grief mechanism you could use in a map.

Practical Example: Proximity Alarm

Put this in a command block set to repeat (covered next lesson):

/execute if entity @e[type=minecraft:zombie,distance=..15] run title @a actionbar {"text":"⚠ Zombie Nearby!","color":"red"}

Whenever a zombie comes within 15 blocks, a warning appears on screen for all players.

Practice Challenges

  1. Write a command that gives you a speed boost when you stand on ice
  2. Make a command that kills zombies within 5 blocks of any player
  3. Create a "trap" — detect when a player steps on a pressure plate block, then summon lightning
  4. Write a command that heals players who stand on emerald blocks
  5. Make all players who are in water get night vision automatically