Wiki 9Minecraft Wiki 9Minecraft

Execute Command Recipes and Context Control

How to chain subcommands, shift execution context, and build conditional logic in Bedrock add-ons.

6Sections
2Code examples
4Known errors

The execute command is the backbone of command-driven mechanics in Minecraft Bedrock add-ons, allowing you to alter who is running a command, where it runs, and under what conditions it fires. You reach for it whenever a standard command inside a function file, animation controller, or entity event needs to target dynamic positions, check for specific block states, or compare scoreboard values before acting.

Understanding Execution Context

Every command in Minecraft Bedrock runs within an execution context. This context consists of several hidden variables: the executor (who is running the command, targeted by @s), the execution position (where the command is running, used by ~ ~ ~), the execution rotation (which way the context faces, used by ^ ^ ^), the dimension (Overworld, Nether, or The End), and the anchor point (whether coordinates are measured from the entity's feet or eyes). When a function runs from `tick.json`, the context has no executor, sits at the world spawn point, and defaults to the Overworld.

The modern `execute` syntax operates as a chain of subcommands that modify these context variables one by one from left to right, before finally terminating in a `run` subcommand. A common mistake when transitioning from older add-on formats is assuming that changing the executor automatically moves the execution position. In current Bedrock syntax, `as` and `at` are strictly decoupled. If you change the executor to a player using `as @p`, the position remains wherever the command started until you explicitly move it using `at @s`.

Subcommands can also fork the execution chain. If `as @e[type=minecraft:zombie]` matches ten zombies, the remainder of the `execute` chain runs ten separate times, once for each zombie. Understanding how and when your chain forks is critical for keeping tick performance healthy in large behaviour packs.

SubcommandWhat it doesNotes
as <target>Changes the executor (@s) to the matched entity or entities.Does not change position, rotation, or dimension.
at <target>Moves position, rotation, and dimension to match the target.Does not change who @s refers to.
positioned <x y z>Sets the execution position using world, relative (~), or local (^) coordinates.Can also use 'positioned as <target>' to copy only the coordinates of an entity.
align <axes>Floors the execution coordinates along the specified axes (x, y, z, or combinations like xz).Useful for snapping entity positions to the exact corner of a block grid.
anchored <eyes|feet>Shifts the origin for local coordinates (^ ^ ^) to the executor's eye level or foot level.Resets back to feet if 'at' or 'positioned' is called later in the chain.
facing <x y z|entity>Changes the execution rotation to look toward a coordinate or another entity's eyes or feet.Does not rotate the actual entity unless paired with a teleport command.
rotated <yaw pitch>Overrides the execution rotation with exact or relative degree values.Also accepts 'rotated as <target>' to copy another entity's facing direction.
in <dimension>Shifts execution to overworld, nether, or the_end.Coordinates are preserved directly without the 8:1 Nether scaling factor.

Context Shifting and Local Coordinates

One of the most frequent uses of `execute` in custom entities and items is raycasting or projecting effects in front of a player's view. To do this accurately, you must combine `as`, `at`, `anchored`, and `positioned` in a specific order. Because `at @s` resets the anchor point to the entity's feet, you must always place `anchored eyes` after `at @s`, never before it.

Once anchored to the eyes, local coordinates (`^left ^up ^forward`) project outward along the executor's line of sight. However, if you immediately spawn an entity or particle using `run particle`, some commands ignore the eye anchor offset unless you bake that offset into the actual execution position. By adding `positioned ^ ^ ^3` into the chain, you physically move the execution point three blocks forward from the eyes, allowing subsequent subcommands or the final `run` command to use simple `~ ~ ~` coordinates at that exact projected spot.

When building mechanics that interact with the block grid—such as custom miner entities or block-placing spells—combine `positioned` with `align xyz`. An entity standing on a block might be at `12.45, 64.0, -8.92`. Running `align xz positioned ~0.5 ~ ~0.5` snaps the context to the exact horizontal center of that block space (`12.5, 64.0, -8.5`), ensuring structures, particles, or summoned block-marker entities align cleanly with the world grid.

Conditional Guard Clauses: If and Unless

The `if` and `unless` subcommands act as gatekeepers inside an execution chain. You can place as many of them in a single command as you need; the chain only proceeds to the next link if every condition passes. This removes the need for intermediate scoreboard tags just to check multiple world states at once.

There are four condition types available in Bedrock: `block`, `blocks`, `entity`, and `score`. The `block` condition checks a single coordinate for a block identifier, and optionally accepts block states in square brackets, such as `minecraft:lit_furnace["facing_direction"=2]`. The `blocks` condition compares a 3D volume of the world against another template volume, matching either `all` blocks or `masked` (non-air) blocks. The `entity` condition passes if at least one entity matches the target selector.

The `score` condition compares scoreboard values without mutating them. You can compare two different entities' scores using relational operators (`<`, `<=`, `=`, `>=`, `>`) or check if a single score falls within a static inclusive range using `matches`. In Bedrock, a range is written with two dots: `1..10` checks for values between 1 and 10, `5..` checks for 5 or higher, and `..0` checks for 0 or lower, including negative numbers.

Condition SyntaxWhat it evaluatesExample
if block <pos> <block> [states]True if the block at the target position matches the ID and optional block states.if block ~ ~-1 ~ minecraft:grass_block
if blocks <begin> <end> <dest> <all|masked>True if the source volume from begin to end matches the volume starting at dest.if blocks ~-1 ~ ~-1 ~1 ~2 ~1 0 64 0 masked
if entity <target>True if the selector resolves to at least one existing entity.if entity @e[type=minecraft:villager,r=10]
if score <targetA> <objA> <op> <targetB> <objB>True if the relational comparison (<, <=, =, >=, >) between two tracked scores holds.if score @s mana >= @s spell_cost
if score <target> <obj> matches <range>True if the entity's score falls within the specified integer range.if score @s cooldown matches 1..20

Practical Recipe: Multi-Condition AoE Ability in an Entity

Inside behaviour pack entity files (`BP/entities/*.json`) and animation controllers (`BP/animation_controllers/*.json`), the `run_command` method lets an entity run a list of commands when an event fires or a state is entered. While the entity itself is already `@s`, its execution position is not always guaranteed to follow its current rotation or eye height unless you explicitly build an `execute` chain.

The following example shows a custom mage entity definition that triggers an area-of-effect attack when the `custom:cast_shockwave` event is called. The first command checks that the mage is standing on solid ground (`unless block ~ ~-0.1 ~ minecraft:air`) and has enough mana on the scoreboard (`if score @s mana matches 20..`). If both pass, it shifts the context to all players within 6 blocks who are not in Creative mode, damages them, and plays a sound at their locations. The second command deducts the mana cost only if a target was actually present to trigger the cast.

BP/entities/shockwave_mage.json
{
  "format_version": "1.20.40",
  "minecraft:entity": {
    "description": {
      "identifier": "custom:shockwave_mage",
      "is_spawnable": true,
      "is_summonable": true
    },
    "components": {
      "minecraft:health": {
        "value": 40,
        "max": 40
      },
      "minecraft:movement": {
        "value": 0.25
      }
    },
    "events": {
      "custom:cast_shockwave": {
        "queue_command": {
          "command": [
            "execute at @s unless block ~ ~-0.1 ~ minecraft:air if score @s mana matches 20.. as @a[r=6,m=!c] at @s run damage @s 6 magic entity @e[type=custom:shockwave_mage,c=1]",
            "execute at @s unless block ~ ~-0.1 ~ minecraft:air if score @s mana matches 20.. if entity @a[r=6,m=!c] run playsound mob.evocation_illager.cast_spell @a[r=16] ~ ~ ~ 1.0 0.8",
            "execute at @s unless block ~ ~-0.1 ~ minecraft:air if score @s mana matches 20.. if entity @a[r=6,m=!c] run scoreboard players remove @s mana 20"
          ]
        }
      }
    }
  }
}

Entity-to-Entity Interactions and Self-Exclusion

A common hurdle when writing `execute` chains is keeping track of `@s` when one entity needs to affect another. Once you call `as @e[type=...]`, the original executor is overwritten for the rest of the command. If you need a zombie to buff all other nearby zombies without buffing itself, you cannot simply exclude `@s` inside the target selector.

The standard Bedrock recipe for self-exclusion and dual-entity targeting is the temporary tag swap. Before entering the `execute` chain that switches context, you assign a temporary tag (such as `source_caster`) to `@s`. You then move the execution position to `@s`, search for targets that do not have that tag (`tag=!source_caster`), run your effects, and immediately remove the `source_caster` tag on the next line of your function or command array. Because commands inside a single `.mcfunction` file or `queue_command` array execute sequentially within the same game tick, the tag is added and cleaned up instantaneously before any other entity processes its turn.

This pattern is also how you make entities face toward or away from a caller. By tagging the caller as `caller`, switching context `as` and `at` the surrounding targets, and using `facing entity @e[tag=caller,c=1] feet`, you can use `tp @s ^ ^ ^-0.5` to push all surrounding mobs directly away from the center of the caller entity.

BP/animation_controllers/repulse_shield.json
{
  "format_version": "1.10.0",
  "animation_controllers": {
    "controller.animation.repulse_shield": {
      "initial_state": "idle",
      "states": {
        "idle": {
          "transitions": [
            {
              "pulsing": "query.is_sneaking"
            }
          ]
        },
        "pulsing": {
          "on_entry": [
            "/tag @s add repulse_origin",
            "/execute at @s as @e[r=5,tag=!repulse_origin,family=monster] at @s facing entity @e[tag=repulse_origin,c=1] feet run tp @s ^ ^0.2 ^-1.2",
            "/tag @s remove repulse_origin"
          ],
          "transitions": [
            {
              "idle": "!query.is_sneaking"
            }
          ]
        }
      }
    }
  }
}

Performance Best Practices for Tick Functions

When running `execute` chains every tick via `BP/functions/tick.json`, ordering your subcommands from cheapest to most expensive prevents server lag. Target selectors that scan the entire loaded world—such as `@e` without a `type` or `r` (radius) argument—force the game engine to iterate over every item drop, mob, and projectile currently active.

Always filter by `type` or `tag` inside the initial selector rather than using a broad selector followed by `if entity`. Furthermore, if an `execute` chain includes both a scoreboard check (`if score`) and a world block check (`if block`), put the scoreboard check first if it is likely to fail most of the time. Scoreboard lookups in memory are fast, and failing the `if score` check early prevents the command from shifting coordinates or querying chunk block data unnecessarily.

Finally, avoid repeating identical `execute` prefixes across ten lines of a `.mcfunction` file. If five different commands all require the exact same complex `execute as @a[tag=in_arena] at @s if block ~ ~-1 ~ minecraft:gold_block` check, have that single `execute` command run a secondary function (`run function arena/gold_pad_reward`). Inside that child function, `@s` and the execution position are already set to the matching player, allowing you to write direct commands without re-evaluating the selector and block condition five times.

Which versions this applies to

Applies to Minecraft Bedrock 1.19.50 and newer using the modern execute syntax. No experimental toggles are required. Note that functions, entity definitions, and animation controllers with format_version or min_engine_version below 1.19.50 may still attempt to parse the legacy execute syntax unless updated.

When it does not work

What you seeWhyThe fix
Content Log error: "Syntax error: Unexpected '@a': at 'execute >>@a<< ~ ~ ~'"You are using the pre-1.19.50 legacy execute syntax inside a behaviour pack whose manifest min_engine_version or entity format_version is 1.19.50 or higher.Rewrite the command using modern subcommands: replace 'execute @a ~ ~ ~ <command>' with 'execute as @a at @s run <command>'.
Commands using ~ ~ ~ or radius selectors (r=5) execute at world spawn (0, 0, 0) instead of around the target entity.You used 'execute as @e[...]' without following it with 'at @s'. Changing the executor with 'as' only changes who @s is, leaving the physical execution coordinates at the caller's location or world origin.Add 'at @s' immediately after your 'as <target>' subcommand whenever the command or selector relies on the target's physical position.
Local coordinates (^ ^ ^5) spawn particles or entities at the player's feet instead of their crosshair line of sight.You placed 'anchored eyes' before 'at @s' in the execute chain, or omitted 'anchored eyes' entirely. Calling 'at <target>' resets the execution anchor back to the entity's feet.Order the chain as 'execute as @a at @s anchored eyes positioned ^ ^ ^5 run ...' so the eye anchor is applied after the position update.
Content Log error: "Failed to execute 'execute' as [Entity]" or block condition always fails in unloaded areas.An 'if block' or 'positioned' subcommand tried to evaluate coordinates in an unloaded chunk, or the final command after 'run' had a leading forward slash.Remove any leading '/' after 'run' (write 'run say hi', not 'run /say hi'), and ensure commands affecting distant coordinates stay within loaded ticking areas or player simulation distance.

Reference, straight from the game files

Read out of the game itself, so the ids match the version you are building for.