Andrew Welch
Published , updated · 5 min read · RSS Feed
Please consider 🎗 sponsoring me 🎗 to keep writing articles like this.
Exploring the Craft CMS Console Command Line Interface (CLI)
Craft CMS comes with many useful commands that can save you time, and make your life easier. In this article, you’ll learn how to stop worrying and love the CLI
The commands in this article are current as of Craft CMS 4.3.6.1
Craft CMS comes with a wonderful console command line interface (CLI), but some people fear CLI’s in general, and others may not fully appreciate what the Craft CLI can do for you. Fortunately, the best way to overcome both is through understanding.
This article goes into depth explaining what the Craft CLI is, and details the commands that are available to you. So let’s dive right in!
Link When might we want to use the Craft CLI?
To fully appreciate why the Craft CLI can be so useful, we need to understand a bit about how it works, and how regular web requests work.
For a regular web request, the web server handles the request, handing off the processing of PHP to a separate process (usually php-fpm). Craft CMS is written in PHP, and also the Twig templates we write are compiled down to PHP.
So suffice it to say that for any given web request, there will typically be a fair bit of PHP that ends up running on our web server. Since web requests are external, untrusted requests there is a memory_limit and a max_execution_time for each request, so that our server is not overwhelmed.
While this is normally wonderful, when we need to perform intensive operations like multiple image transforms, re-saving of entries, and especially Craft CMS & plugin updates, it can become a hinderance. Timeouts happen, queue jobs fail, and it’s no fun for anyone.
Additionally, when we have occasion to run tasks at regular intervals or when we deploy changes to our website, doing things like going in and clearing caches by hand gets old quick.
The Craft CMS console command line interface to the rescue:
- Tasks run via CLI typically have no memory_limit or max_execution_time, because they are run by an internal, trusted source, so you they won’t timeout or run out of memory
- CLI tasks can easily be triggered at regular intervals (perhaps via cron) or triggered when certain events happen, in an automated way that doesn’t require any user intervention
So for any time consuming or memory intensive process, as well as whenever we need tasks to happen in an automated way, the CLI is our friend.
Link What exactly is the Craft CLI?
Now that we know when we might want to use the Craft CLI, let’s have a peek behind the curtains to see exactly what it is.
When we set up a new Craft CMS project, there is a curious file placed in the project root directory:
-rwxr--r-- 1 vagrant vagrant 501 Nov 17 2022 craft
Let’s have a look at what the craft command is, exactly:
#!/usr/bin/env php
<?php
/**
* Craft console bootstrap file
*/
// Load shared bootstrap
require __DIR__ . '/bootstrap.php';
// Load and run Craft
/** @var craft\console\Application $app */
$app = require CRAFT_VENDOR_PATH . '/craftcms/cms/bootstrap/console.php';
$exitCode = $app->run();
exit($exitCode);
The first line #!/usr/bin/env php is called a shebang (this was a thing long before Ricky Martin) which essentially just tells the console that the script is PHP, and to execute in the current environment.
The rest of the code is very similar to what is in our web/index.php, which makes sense, because we’re running Craft in both cases. Just think of the craft command as the CLI equivalent of the web’s index.php. Both bootstrap Craft, and run it.
./craft
The odd looking ./ is a Unix-ism that means “in this current directory”. I know, I know. You’re already in that current directory, why doesn’t it know this already? Just accept it and let it happen, because if we don’t use it we’ll see:
$ craft
-bash: craft: command not found
It’s a long story as to why this is the case, but it has to do with how Unix paths work. Typing just ./craft on its own just lists all of the available commands (technically this is the same as ./craft help).
If you see a Permission denied error like this:
$ ./craft
-bash: ./craft: Permission denied
This just means that the craft script doesn’t have executable permissions. You can fix that with the following:
chmod a+x craft
For more information about Unix and Craft permissions, check out the Hardening Craft CMS Permissions article.
So assuming we’ve typed it successfully, we’ll see something like this:
$ ./craft
This is Yii version 2.0.47.
The following commands are available:
- backup DEPRECATED. Use `db/backup` instead.
backup/db (default) DEPRECATED. Use `db/backup` instead.
- cache Allows you to flush cache.
cache/flush Flushes given cache components.
cache/flush-all Flushes all caches registered in the system.
cache/flush-schema Clears DB schema cache for a given connection component.
cache/index (default) Lists the caches that can be flushed.
- clear-caches Allows you to clear various Craft caches.
clear-caches/all Clear all caches.
clear-caches/asset Asset caches
clear-caches/asset-indexing-data Asset indexing data
clear-caches/compiled-classes Compiled classes
clear-caches/compiled-templates Compiled templates
clear-caches/cp-resources Control panel resources
clear-caches/data Data caches
clear-caches/index (default) Lists the caches that can be cleared.
clear-caches/seomatic-frontendtemplate-caches SEOmatic frontend template caches
clear-caches/seomatic-metabundle-caches SEOmatic metadata caches
clear-caches/seomatic-sitemap-caches SEOmatic sitemap caches
clear-caches/temp-files Temp files
clear-caches/transform-indexes Asset transform index
- clear-deprecations Clears all deprecation warnings.
clear-deprecations/index (default) Clears all deprecation warnings.
- db Performs database operations.
db/backup Creates a new database backup.
db/convert-charset Converts tables’ character sets and collations. (MySQL only)
db/drop-all-tables Drops all tables in the database.
db/restore Restores a database backup.
- elements Manages elements.
elements/delete Deletes an element by its ID.
elements/restore Restores an element by its ID.
- fixture Allows you to manage test fixtures.
fixture/load (default) Loads the specified fixture data.
fixture/unload Unloads the specified fixtures.
- gc Allows you to manage garbage collection.
gc/run (default) Runs garbage collection.
- graphql Allows you to manage GraphQL schemas.
graphql/create-token Creates a new authorization token for a schema.
graphql/dump-schema Dumps a given GraphQL schema to a file.
graphql/list-schemas Lists all GraphQL schemas.
graphql/print-schema Prints a given GraphQL schema.
- help Provides help information about console commands.
help/index (default) Displays available commands or the detailed information
help/list List all available controllers and actions in machine readable format.
help/list-action-options List all available options for the $action in machine readable format.
help/usage Displays usage information for $action.
- index-assets Allows you to re-index assets in volumes.
index-assets/all Re-indexes assets across all volumes.
index-assets/cleanup Removes all CLI indexing sessions.
index-assets/one (default) Re-indexes assets from the given volume handle.
- install Craft CMS CLI installer.
install/check Checks whether Craft is already installed.
install/craft (default) Runs the install migration.
install/plugin DEPRECATED. Use `plugin/install` instead.
- invalidate-tags Allows you to invalidate cache tags.
invalidate-tags/all Clear all caches.
invalidate-tags/graphql GraphQL queries
invalidate-tags/index (default) Lists the caches that can be cleared.
invalidate-tags/template Template caches
- mailer Allows for testing mailer settings via the CLI.
mailer/test Tests sending an email with the current mailer settings.
- migrate Manages Craft and plugin migrations.
migrate/all Runs all pending Craft, plugin, and content migrations.
migrate/create Creates a new migration.
migrate/down Downgrades the application by reverting old migrations.
migrate/fresh Not supported.
migrate/history Displays the migration history.
migrate/mark Modifies the migration history to the specified version.
migrate/new Displays the un-applied new migrations.
migrate/redo Redoes the last few migrations.
migrate/to Upgrades or downgrades till the specified version.
migrate/up (default) Upgrades Craft by applying new migrations.
- off Takes the system offline.
off/index (default) Disables `system.live` project config value—bypassing any `allowAdminChanges` config setting
- on Takes the system online.
on/index (default) Turns the system on.
- plugin Manages plugins.
plugin/disable Disables a plugin.
plugin/enable Enables a plugin.
plugin/install Installs a plugin.
plugin/list (default) Lists all plugins.
plugin/uninstall Uninstalls a plugin.
- project-config Manages the Project Config.
project-config/apply Applies project config file changes.
project-config/diff Outputs a diff of the pending project config YAML changes.
project-config/export Exports the entire project config to a single file.
project-config/get Outputs a project config value.
project-config/rebuild Rebuilds the project config.
project-config/remove Removes a project config value.
project-config/set Sets a project config value.
project-config/sync DEPRECATED. Use `project-config/apply` instead.
project-config/touch Updates the `dateModified` value in `config/project/project.yaml`, attempting to resolve a Git conflict for it.
project-config/write Writes out the currently-loaded project config as YAML files to the `config/project/` folder, discarding any
pending YAML changes.
- queue Manages the queue.
queue/exec Executes a job.
queue/info (default) Info about queue status.
queue/listen Listens for new jobs added to the queue and runs them.
queue/release Releases job(s) from the queue.
queue/retry Re-adds a failed job(s) to the queue.
queue/run Runs all jobs in the queue.
- resave Allows you to bulk-save elements.
resave/assets Re-saves assets.
resave/categories Re-saves categories.
resave/entries Re-saves entries.
resave/matrix-blocks Re-saves Matrix blocks.
resave/navigation-nodes Re-saves Navigation nodes.
resave/supertable-blocks Re-saves Super Table blocks.
resave/tags Re-saves tags.
resave/users Re-saves users.
- restore DEPRECATED. Use `db/restore` instead.
restore/db (default) DEPRECATED. Use `db/restore` instead.
- serve Runs the built-in PHP web server.
serve/index (default) Runs PHP built-in web server.
- setup Craft CMS setup installer.
setup/app-id Generates a new application ID and saves it in the `.env` file.
setup/db Alias for setup/db-creds.
setup/db-cache-table Creates a database table for storing DB caches.
setup/db-creds Stores new DB connection settings to the `.env` file.
setup/index (default) Sets up all the things.
setup/keys Generates an application ID and security key (if they don’t exist), and saves them in the `.env` file.
setup/php-session-table Creates a database table for storing PHP session information.
setup/security-key Generates a new security key and saves it in the `.env` file.
setup/welcome Called from the `post-create-project-cmd` Composer hook.
- tests Provides support resources for testing both Craft’s services and your project’s Craft implementation.
tests/setup Sets up a test suite for the current project.
tests/test Don't use this method - it won't actually execute anything.
- up Runs pending migrations and applies pending project config changes.
up/index (default) Runs pending migrations and applies pending project config changes.
- update Updates Craft and plugins.
update/composer-install Installs dependencies based on the current `composer.json` & `composer.lock`.
update/info Displays info about available updates.
update/update (default) Updates Craft and/or plugins.
- users Manages user accounts.
users/activation-url Generates an activation URL for a pending user.
users/create Creates a user.
users/delete Deletes a user.
users/impersonate Generates a URL to impersonate a user.
users/list-admins Lists admin users.
users/logout-all Logs all users out of the system.
users/password-reset-url Generates a password reset URL for a user.
users/set-password Changes a user’s password.
- utils/ascii-filenames Converts all non-ASCII asset filenames to ASCII.
utils/ascii-filenames/index (default) Converts all non-ASCII asset filenames to ASCII.
- utils/fix-element-uids Utilities
utils/fix-element-uids/index (default) Ensures all elements UIDs are unique.
- utils/fix-field-layout-uids Fixes any duplicate UUIDs found within field layout components in the project config.
utils/fix-field-layout-uids/index (default) Fixes any duplicate UUIDs found within field layout components in the project config.
- utils/prune-provisional-drafts Prunes provisional drafts for elements that have more than one per user.
utils/prune-provisional-drafts/index (default) Prunes provisional drafts for elements that have more than one per user.
- utils/prune-revisions Prunes excess element revisions.
utils/prune-revisions/index (default) Prunes excess element revisions.
- utils/repair Repairs data.
utils/repair/category-group-structure Repairs structure data for a category group.
utils/repair/project-config Repairs double-packed associative arrays in the project config.
utils/repair/section-structure Repairs structure data for a section.
- utils/update-usernames Updates all users’ usernames to ensure they match their email address.
utils/update-usernames/index (default) Updates all users’ usernames to ensure they match their email address.
To see the help of each command, enter:
craft help <command-name>
Phew, that’s a lot! These are all of the built-in CLI commands as of Craft CMS 4.3.6.1; there may be more added later, and plugins can add their own CLI commands too!
We’ll cover what each one does, but the single most important CLI command is:
$ ./craft help <command-name>
If we use the ./craft help command for a top level command, we might see something like this:
$ ./craft help update
DESCRIPTION
Updates Craft and plugins.
SUB-COMMANDS
- update/composer-install Installs dependencies based on the current `composer.json` & `composer.lock`.
- update/info Displays info about available updates.
- update/update (default) Updates Craft and/or plugins.
To see the detailed information about individual sub-commands, enter:
craft help <sub-command>
But if we’re a bit more specific with it, and supply the full sub-command such as ./craft help update/composer-install we’ll see a whole lot more help on that specific command, the parameters it takes, etc.:
$ ./craft help update/composer-install
DESCRIPTION
Installs dependencies based on the current composer.json & composer.lock.
USAGE
craft update/composer-install [...options...]
OPTIONS
--appconfig: string
custom application configuration file path.
If not set, default application configuration is used.
--color: boolean, 0 or 1
whether to enable ANSI color in the output.
If not set, ANSI color will only be enabled for terminals that support it.
--help, -h: boolean, 0 or 1 (defaults to 0)
whether to display help information about current command.
--interactive: boolean, 0 or 1 (defaults to 1)
whether to run the command interactively.
--silent-exit-on-exception: boolean, 0 or 1
if true - script finish with `ExitCode::OK` in case of exception.
false - `ExitCode::UNSPECIFIED_ERROR`.
Default: `YII_ENV_TEST`
I consider the help command to be the most important command, because we can use it to figure out how to use all of the other commands!
Let’s check out the available commands, and what we might use them for.
Link backup
You can also back up and restore the database via a console command! Have a look at some of the examples that Brandon noted in the FR:
# create backup in the given folder
./craft db/backup ./backups
# create backup in working directory with custom filename
./craft db/backup backup.sql
# create backup in specific location
./craft db/backup ./backups/backup.sql
# create backup in the storage/backups/ folder
./craft db/backup
This can be a great addition as a cron job or other automated execution to back up the Craft database!
Link cache
You’re probably not going to use this command much, if at all. It’s actually coming from Yii2 and deals specifically with the Yii2 data cache, which isn’t used for much of anything in Craft (though many plugins do leverage it).
It has nothing to do with what you probably think of in terms of caching & Craft, which is the {% cache %} tag. For more on that, check out the The Craft {% cache %} Tag In-Depth article.
In addition, the clear-caches command (see below) can clear the Yii2 data cache anyway so… nothing to see here, move along.
Link clear-caches
The clear-caches command is one that I PR’d to the Craft core. It is exactly analogous to the Clear Caches Utility; anything you can clear from the CP, you can now clear from the CLI.
This is especially useful if you want to clear caches when you deploy changes to the website, for example. See the Composer Scripts section below for more on this.
Pro tip: If you see the error Error clearing cache Control Panel resources it’s because for CLI requests, you need to tell Craft where your /cpresources directory is in your general.php file:
'resourceBasePath' => dirname(__DIR__) . '/web/cpresources',
You can find a discussion about the above on this GitHub issue.
Link gc
The gc command is a bit on the obtuse side, so it’s likely only in certain circumstances that you’ll have a use for it. If you use the Soft Deletes feature, and you want to run garbage collection manually or on a fixed time schedule, this is the command for you.
What garbage collection does is permanently deletes anything that was soft deleted and expired. Instead of it having a chance of running on any given web request (and thus potentially slowing down the web request), you can control when and how it runs.
Link help
We’ve talked about this.
Link index-assets
The index-assets is a PR from Ryan McQuen and does the same job as the Asset Indexes Utility, but it does so via the CLI.
This can be especially handy because asset indexing can take a long time, and will run more reliably via the CLI than web request because it won’t time out or run out of memory during indexing.
Link install
The install command can be used to install Craft itself (which runs the install migration that sets up the database structure) or to install a plugin. To install a plugin, it needs to already be in your composer.json, but this gives you a way to do it from the CLI, perhaps as part of your boilerplate setup.
If you want to install Craft as part of some larger automated process, you can run it non-interactively, for example:
./craft install \
--interactive=0 \
--email="admin@example.com" \
--username="admin" \
--password="secret" \
--siteName="Craft4" \
--siteUrl="$SITE_URL" \
--language="en"
N.B.: the \ in the above example isn’t unique to the ./craft install command, it’s a generic way to have a multi-line command in Unix shells.
Check out the Setting up a New Craft CMS 3 Project article for more on setting up your own Craft CMS boilerplate setup.
Link migrate
The migrate command gives you CLI control over your migrations. The most common use-case here is to run migrations as part of your automated build deployment, so you aren’t having to race to the /admin CP to run the migrations when you push updates to Craft CMS or plugins into production.
In this context, a “migration” means a set of database commands that Craft and/or plugins run to change the structure of the database. This is needed from time to time as features are added, or bugs are fixed.
Your website won’t be available to the public until migrations are run, if Craft or plugins have pending migrations.
There’s no way to predict when Craft or plugins will need to do a migration, so it’s best done in an automated way every time you do updates. See the Composer Scripts section below for more on this.
Link project-config
The project-config/apply is again a command you’ll most likely run as part of your deployment process to sync any Project Config changes.
Your Project Config changes won’t be available to the public until Project Config changes are applied.
Avoid the pulse-quickening race to the /admin CP to ensure that your Project Config changes are applied in production when you push them. See the Composer Scripts section below for more on this.
Also helpful is the project-config/rebuild command which will rebuild your Project Config files from the database if something has gotten out of sync.
Link queue
The queue command allows you to interact with the Craft CMS queue and queue jobs via the CLI. If you’re having issues with stuck queue jobs (which run via web requests, as discussed above), check out the Robust queue job handling in Craft CMS article.
You can then turn off the runQueueAutomatically general.php config setting, and have the queue run in the background via the CLI via ./craft queue/listen
If you don’t want to go to these lengths, the Async Queue plugin from Oliver Stark can give you the same results.
Link resave
The resave command is the newest Craft CMS CLI command. It once again allows you to run the lengthy and memory intensive “Re-saving Elements” task via the CLI. See this GitHub issue for context.
I think we’re seeing a pattern here with the CLI being useful for lengthy and/or memory intensive operations.
Link serve
The serve command is a PR from Mark Huot that ensure the Yii2 serve command works with Craft CMS. What does that mean?
It means that with zero local development environment, you can start serving Craft up from a given host/port. Handy for getting things up and running in a jiffy!
Link setup
The setup command allows you to set up your .env file for environment-specific settings, including database settings, and other “secrets” or things that vary from environment to environment.
This is covered in detail in the Craft Installation instructions, and is a nice interactive way to fill in what’s needed without having to create & edit the .env file directly with an editor.
Link update
The update command is a way to ease the pain of running Composer via the CP as Pixel & Tonic works on their Update Service. This one deserves mentioning what the sub-commands do explicitly:
- update/update — this does the exact same thing as clicking on the Update button in the CP, but running it via the CLI so you don’t have to worry about Composer timing out or running out of memory
- update/composer-install — this is something you’re use when you deploy Craft CMS, effectively doing the same thing as composer install but for server setups where Composer is not installed.
These commands are useful if you don’t have Composer installed locally or on your server (or just don’t want to deal with Composer), but have run into issues with updating via the CP.
It’s also useful if you want the deployment process to be automated as discussed in the DEPLOYMENT section of the Setting up a New Craft CMS 3 Project article, but again, don’t have Composer available to you.
Link Composer Scripts
You can run these commands directly as part of your deployment process via a shell script or the like, but you can also leverage Composer.
Composer has a concept of Scripts that can be executed when various things happen. For example, let’s say that you update your Craft CMS site in local development, and then push the composer.lock file to production.
On production, you’d then run the composer install command, and exactly what you installed & tested in local development will then be installed on production.
You might add something like this to the "scripts" section of your composer.json:
"scripts": {
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php craft setup/welcome"
],
"post-update-cmd": [
"@php craft migrate/all",
"@php craft project-config/sync",
"@php craft clear-caches/all"
],
"post-install-cmd": [
"@php craft migrate/all",
"@php craft project-config/sync",
"@php craft clear-caches/all"
]
}
What this means is that any time composer update or composer install are run, it will run Craft CLI commands to:
- Run all pending migrations
- Sync your project.yaml changes
- Clear all caches
Boom, instant automated deployment. The nice part about this is that it’ll run in local dev, too.
Pro tip: if you do your composer install inside of a buddy.works container or the like, where you don’t want migrations to be run (there may be no database at all), you can use:
composer install --no-scripts
In this way, your composer install will happen, but none of the Composer scripts will be run in an environment where they may not execute properly.
Link Wrapping up
That’s all she wrote! Hopefully this article has helped demystify the Craft CMS CLI a bit, and given you some ideas of how it can make your development and deployment process better.
Have no fear… the CLI is here! Embrace it where it can help automate things for you, and make your life easier.
Happy deploying!