How to testfor and execute the effect in the single command block?

I want to do the following but not add a comparator linking the testfor to the setblock, instead I wish to have them in the same space.
/execute @p ~ ~ ~ testforblock ~ ~-1 ~ grass /setblock ~ ~-1 ~ dirt
Is this possible?
Best Answer
No, you cannot chain testforblock
with more commands just like that, but there are other ways to do it.
1. execute
's detect
keyword
The execute
command has a special detect
keyword that allows you to do exactly what you want. It is essentially a testforblock
query inside an execute.
execute <entity> <x> <y> <z> detect <x2> <y2> <z2> <block> <data> <command>
This will run <command>
on <entity>
only if <block>
(with <data>
) is present at <x2> <y2> <z2>
1. So for your example, you want to use
execute @p ~ ~ ~ detect ~ ~-1 ~ grass 0 setblock ~ ~-1 ~ dirt
1) If you use tilde notation for relative coordinates, the second set of coordinates is relative to the first set (in this case the position of @p
).
2. fill
's replace
option
An alternate way to do what you want to do is to use the fill
command with the replace
option (This is more limited in scope, and I only include it here for completeness):
fill <x1> <y1> <z1> <x2> <y2> <z2> <TileName> <dataValue> replace [replaceTileName] [replaceDataValue]
If both coordinate sets are identical, it will only affect a single block. So, to replace grass below the player with dirt, you can use
execute @p ~ ~ ~ fill ~ ~-1 ~ ~ ~-1 ~ dirt 0 replace grass 0
Pictures about "How to testfor and execute the effect in the single command block?"



How do you Testfor with command blocks?
How to Enter the CommandHow do you execute a command at a block?
How to get a Command BlockHow To Use '/testfor' \u0026 'testforblock' Command In Minecraft Bedrock | Command Tutorial #24
Sources: Stack Exchange - This article follows the attribution requirements of Stack Exchange and is licensed under CC BY-SA 3.0.
Images: Pressmaster, Pressmaster, Erik Mclean, Aidan Roof