Automatically running a Minecraft command

Is there a way to automatically run a Minecraft command when starting a new game, loading an existing world, joining a server, or re-spawning?

For example, is there a way to automatically enable keepInventory instead of having to manually enter it?

Granted, this isn’t the best example because it seems that command happens to be persistent, but there are other commands that people might like to run each time they load a game, and could also be useful for multiplayer games if a command could be run on them when they join a server.

A better example is if you want to automatically get a pickaxe after dying so that you can save time, or if you want to automatically /give users a sword whenever they re-spawn on a deathmatch type server.


This is what Command Blocks are for: they bridge the gap between in-game events and console commands. You program one with the desired console command, and hook it up to any sort of redstone trigger. So for example, if you put one next to your spawn point with a button attached, you can give yourself a pickaxe when you respawn there or whenever you need one.

There's a good tutorial with some examples on the minecraft wiki.