Magento 2 CLI – Commands list, Syntax, and steps to create Custom Command

0

 

As a developer using Magento 2, you may have encountered the challenge of finding the right Magento CLI commands. It can be time-consuming and frustrating to search for the right commands on various websites when there is no centralized resource that provides a comprehensive Magento 2 command list.

If you’ve also been through the same situation, you’re not alone!

As you may already know, Magento 2 Command-Line Interface (CLI) offers a convenient and efficient way to execute various tasks, including installing the platform, managing modules, themes, extensions, and configuring the store.

By utilizing the CLI commands, you can save time and effort while also enhancing your Magento 2 development experience.

In this blog post, we’ll provide you with a comprehensive list of Magento 2 CLI commands that you can use as a reference whenever you need them. Moreover, we’ll also guide you on how to add your custom CLI commands in Magento 2.

So, let’s dive into it and streamline your Magento 2 development workflow!

What Is Magento 2 CLI

A command line interface (CLI) is a text-based user interface (UI). Just like how driving a car requires you to interact with various controls, such as the steering wheel, pedals, and dashboard, the Magento 2 CLI allows you to interact with your computer or application using text-based commands.

For example, you can use the CLI to run programs, manage computer files, and configure settings, just like how you can use the controls of a car to navigate the road, accelerate or brake, and adjust the car’s settings.

Magento 2 has one command-line interface that performs installation and configuration tasks, including caching, installing, and more.

One specific example of using the Magento 2 CLI is clearing the cache. This is similar to how a driver may need to clear the windshield of a car to remove any dirt or debris that may be obstructing their view. By using the cache:clean command, you can remove any cached data that may be obstructing your view of your Magento 2 site, allowing you to see any changes you’ve made immediately.

Prerequisites for CLI (Command Line Interface) In Magento 2

Before you begin using the CLI, make sure that:

  • Your system meets the requirements discussed in System Requirements in the Installation guide.
  • You have fulfilled all the requirements mentioned in the Installation guide’s Prerequisites section.
  • After logging in to the Adobe Commerce server, you’ve switched to a user with permission to write to the Commerce file system. You can learn how to do this in the Installation guide’s File ownership and permissions section.

How to Access Files Through Magento CLI

To access the Magento 2 Command-Line Interface (CLI), you need to have SSH (Secure Shell) access to your server.

Note: Once you have SSH access, you can log in to your server using a terminal emulator such as PuTTY (for Windows) or Terminal (for macOS and Linux).

Follow these steps to access and run Magento CLI:

The general directory structure for Magento is as follows, which you can use to access your application from the server based on your operating system:

cd <magento_root>/bin

Example:

Ubuntucd /var/www/magento2/bin

CentOScd /var/www/html/magento2/bin

Assusing your store is hosted on Cloudways, follow the steps below to access Magento CLI. For a more detailed guide about SSH, please refer to this guide.

  • Login to your Server and access SSH: Click on the Launch SSH Terminal to open the SSH terminal or access the SSH with any other terminal.

Magento CLI Command

  • Enter your Credentials: Enter the credentials, i.e., Username and Password, under the Master Credentials.

Magento CLI Command 2

  • Access your Magento application and its public folder:

Magento CLI Command 3

Now, you are in the public directory of the Magento 2 application and can run any bin/magento command.

The Magento CLI is located in the <project-root>/bin/ directory of every Magento installation. You can access it from the Magento root directory using the following command:

  1. php bin/magento

Note: Using “php” before bin/magento is optional. But this is only in the latest version of Magento 2 only. Your operating system will automatically find the global PHP variable to execute the command even if you leave it out

Run Magento 2 CLI Command

To run any command, first access the server’s command line interface (CLI), and then navigate to the public directory of the Magento 2 application. Here’s how:

Please add a step here on how to navigate to the public directory of the Magento 2 application.

To run a specific Magento 2 CLI command, run the following command:

bin/magento [command-name] [arguments]

Replace: 

  • [command-name] with the name of the Magento 2 CLI command.
  • [arguments] with any required or optional arguments for the command.

For example, to flush the Magento 2 cache, run the following command:

  1. bin/magento cache:flush

List of Useful Magento 2 Commands and How to Use Them

The Magento 2 CLI commands can be accessed from the command line interface of your server or local environment. All Magento command-line interface (CLI) commands rely on the Magento application and must have access to its context, dependency injections, plug-ins, and so on.

Magento 2 CLI Command Structure:

Here is the basic structure of the Magento 2 CLI command:

bin/magento [option] [arguments]

In this command structure:

  • bin/magento is the path to the Magento 2 CLI executable file.
  • <command> is the name of the CLI command you want to run.
  • [<options>] are the optional parameters you can pass to the command.

Example: php bin/magento indexer:reindex

List All Commands:

First, to check all the list of commands available in Magento 2, run the command below:

  1. bin/magento list

magento2list-commands

You can call bin/magento CLI commands using shortcuts instead of the full command name. For example, you can call bin/magento setup:upgrade using bin/magento s:up, bin/magento s:upg. See shortcut syntax to understand how to use shortcuts with any CLI command.

Here are some of the useful and common Magento commands for managing the Magento application:

Magento 2 Cache Commands

As the name suggests, this Magento 2 command can manipulate Magento’s caching option. You can enable, disable, clean, flush, or check the status of the Magento cache with these commands:

  • Command: magento cache:{enable/disable/clean/flush/status}
CacheCommandShortcutDescription
bin/magento cache:statusbin/magento c:sTo list cache types and their status
bin/magento cache:enablebin/magento c:eTo enable all caches OR any specific cache type
bin/magento cache:disablephp bin/magento c:dTo disable all caches OR any specific cache type
bin/magento cache:cleanbin/magento c:cIt would delete cache types linked with Magento only
bin/magento cache:flushbin/magento c:fDeletes all cache of the same storage

Magento 2 Indexer Commands

The indexer is a widely used option in Magento 2. Previously there wasn’t any method to update indexing manually, but now it can also be done through Magento’s Admin panel. Besides reindexing using the Magento reindex command, you have the option to set indexing mode and to check the status of the indexer via Magento CLI.

  • Command: bin/magento indexer: {status/show-mode/set-mode/reindex/info/reset/show-dimensions-mode/set-dimensions-mode}

Example:

IndexerCommandShortcutDescription
bin/magento indexer:infobin/magento indexer:infoShow list of all indexers
bin/magento indexer:statusbin/magento i:staView status of all indexers or specific indexer only
bin/magento indexer:set‐modebin/magento i:setTo reindex all the indexer or specific indexer only
bin/magento indexer:reindexbin/magento i:reiTo invalidate all the indexer or specific indexer only
bin/magento indexer:show-modebin/magento i:shoFor viewing indexer current configuration

Magento 2 Admin Commands

With Magento 2 Admin Commands, you can create a new admin user, edit or unlock the user that is already created through Magento CLI.

Command:

  • bin/magento admin:user:{create/unlock}
  • bin/magento admin:user:create [–<parameter_name>=<value>, …]

Example:

AdminCommandShortcutDescription
bin/magento admin:user:createbin/magento a:u:cCreate an Administrator
bin/magento admin:user:unlockphp bin/magento a:u:uUnlock Admin Account
bin/magento admin:adobe-ims:statusStatus of Adobe IMS Module
bin/magento admin:adobe-ims:info Information of Adobe IMS Module configuration
bin/magento admin:adobe-ims:enableEnable Adobe IMS Module
bin/magento admin:adobe-ims:disableDisable Adobe IMS Module

Magento 2 Module Commands

This Magento command can be used to enable, disable, uninstall or check the status of all the installed modules through Magento CLI. Disabling or uninstalling a module will fail with this Magento 2 command if there is any dependency on that module.

  • Command: bin/magento module:user:{status/enable/disable/uninstall}

Example:

ModuleCommandShortcutDescription
bin/magento module:statusbin/magento mo:sCheck the status of Magento modules
bin/magento module:enablebin/magento mo:eTo enable specific Magento module
bin/magento module:disablebin/magento mo:dTo disable specific Magento module
bin/magento module:uninstallbin/magento m:uTo uninstall specific Magento module

Magento 2 Cron Command

This Magento 2 command can execute the scheduled Magento Cron jobs manually. You can put this command in the scheduler, so the application’s task can be executed in a timely manner. Speaking of Magento Cron jobs, you might be interested in our guide on how to create, set up, and configure Magento 2 Cron Job.

Command:

  1. magento cron:run

Example:

CronCommandShortcutDescription
bin/magento cron:installbin/magento c:inGenerates and installs crontab for current user
bin/magento cron:removebin/magento c:reRemoves tasks from crontab
bin/magento cron:runbin/magento c:rRuns jobs by schedule

Magento 2 Maintenance Commands

Magento Maintenance Commands can help you keep your website running smoothly. Here are some of the most useful maintenance commands.

  • Command: bin/magento maintenance:{status/enable/disable/allow-ips}

Here are some useful commands:

MaintenanceCommandShortcutDescription
bin/magento maintenance:allow-ipsbin/magento m:aSets maintenance mode exempt IPs
bin/magento maintenance:disablebin/magento ma:dDisables maintenance mode
bin/magento maintenance:enablebin/magento ma:eEnables maintenance mode
bin/magento maintenance:statusbin/magento ma:sDisplays maintenance mode status

Magento 2 Info Commands

By using Magento 2 info commands, users can gain insights to access information about their website and the system running it.

  • Command: bin/magento info:{adminuri/backups/currency/dependencies/language}

Here are some useful info commands:

InfoCommandShortcutDescription
bin/magento info:adminuri bin/magento i:aDisplays the Magento Admin URI
bin/magento info:backups:list bin/magento i:b:lPrints list of available backup files
bin/magento info:currency:list   bin/magento i:c:lDisplays the list of available currencies
bin/magento info:dependencies:show-frameworkbin/magento i:d:show-fShows number of dependencies on Magento framework
bin/magento info:dependencies:show-modules  bin/magento i:d:show-modulesShows a number of dependencies between modules
bin/magento info:dependencies:show-modules-circular  bin/magento i:d:show-circularShows number of circular dependencies between modules
bin/magento info:language:list bin/magento i:l:lDisplays the list of available language locales
bin/magento info:timezone:list bin/magento i:t:lDisplays the list of available timezones

Magento 2 Setup Commands

here are plenty of things that you can do with Magento setup commands.

Here are some useful commands:

SetupCommandShortcutDescription
bin/magento setup:config:set bin/magento s:c:sCreates or modifies the deployment configuration
bin/magento setup:di:compile bin/magento s:d:cGenerates DI configuration and all missing classes that can be auto-generated
bin/magento setup:upgrade bin/magento s:upUpgrades the Magento application, DB data, and schema
bin/magento setup:uninstallbin/magento s:unUninstalls the Magento application
bin/magento setup:install bin/magento s:iInstalls the Magento application
php bin/magento setup:static-content:deployphp bin/magento s:s:dDeploys static view files

Backup Command

This Magento CLI command can back up our application’s code, database, and media files. Backup can be found in your web root’s var/backup/directory.

We also have a full guide on how you can backup your Magento store in just a few steps.

Command:

  1. magento setup:backup ‐‐code ‐‐media ‐‐db

Config Command

This option can be used to make configuration changes in Magento. The changes involve DB parameters, admin URL, etc. You can see your provided values reflected in the app/etc/env.php file.

Command:

  1. magento setup:config:set ‐‐backend‐frontname="admin" ‐‐db‐host="localhost" ‐‐db‐name="example" ‐‐db‐user="example" ‐‐db‐password="example"

Other Magento 2 Setup Commands

  • To generate data for performance testing

Command:

  • magento setup:perf:generate-fixtures
  • bin/magento setup:perf:generate-fixtures {path to profile}

Example:

bin/magento setup:perf:generate-fixtures /var/www/html/magento2/setup/performance-toolkit/profiles/ce/test.xml

  • To generate data, patch and declaration

Commands:

  • setup:db-declaration:generate-patch
  • setup:db-declaration:generate-whitelist
  • setup:db-schema:upgrade
  • setup:db-data:upgrade

Magento 2 Deploy Commands

Magento 2 offers a collection of CLI commands to facilitate the deployment of a store’s static content. This encompasses CSS, JavaScript, HTML files, images, fonts, and various media assets. These commands are also leveraged when performing version upgrades or implementing security patches in Magento 2.

Example:

DeployCommandShortcutDescription
bin/magento deploy:mode:set bin/magento d:m:setSet application mode
bin/magento deploy:mode:showbin/magento d:m:shoDisplays current application mode

Magento 2 Theme Commands

Magento 2 has a powerful theming system that allows you to create custom themes or modify existing ones using HTML, CSS, JavaScript, and XML files.

Command:

php bin/magento theme:uninstall

Shortcut: 

  1. php bin/magento t:u

Other Useful Magento 2 Commands

Apart from the previously mentioned commands, there are numerous other useful CLI commands available in Magento 2, which we’ll explore below.

To generate a translation dictionary:

Command:

  • magento i18n:{collect-phrases/pack/uninstall}
  • bin/magento i18n:collect-phrases [-o|–output=”<csv file path and name>”] [-m|–magento] <path to directory to translate>
  • bin/magento i18n:pack [-m|–mode={merge|replace}] [-d|–allow-duplicates] <source> <locale>

Example:

magento i18n:collect-phrases

To create CSS from LESS:

Command:

  • magento dev:source-theme:deploy
  • bin/magento dev:source-theme:deploy [–type=”…”] [–locale=”…”] [–area=”…”] [–theme=”…”] [file1] … [fileN]

Example:

bin/magento dev:source-theme:deploy –type=”less” –locale=”en_US” –area=”frontend” –theme=”VendorName/themeName” css/styles-l

To run specified automated test:

  • Command: bin/magento dev:tests:run <test>

Example:

bin/magento dev:tests:run integration

To show the list of test:

Example:

bin/magento dev:tests:run –help

To update the layout XML file:

  • Command: bin/magento dev:xml:convert

To install sample data on the Magento application:

  • Command: magento sampledata:install

For managing backend configuration:

  • Command: magento config:{set/sensitive:set/show/}

To check the complete list of Magento commands:

  • Command: bin/magento list

To get help for any particular command:

  • Command: bin/magento help <command>

Example:

  1. bin/magento help cache:enable

If you want more information about Magento 2 commands, you can refer to the official Magento guide . Additionally, if you’re interested in installing Magento 2 on PHP, you can check out our detailed installation guide .

Now that we’ve familiarized ourselves with some popular Magento CLI commands let’s explore how to create your custom command and how to use it.

Fix Magento 2 Commands Not Working

There could be several reasons why Magento 2 commands are not working. Here are some troubleshooting steps you can try:

If you are running any command and nothing is returned, the following are the options to fix this:

Tip💡 Please check the logs to check the actual error that causes the issue.

Check File Permissions

Make sure the files and directories in your Magento 2 installation have the correct permissions. You can use the following command to set the correct permissions:

  1. sudo chmod -R 777 var/ pub/

Enable error reporting

Enable error reporting in your Magento 2 installation. This can help you identify any issues with your installation. To enable error reporting, edit the index.php file in your Magento 2 installation and uncomment the following line:

  1. #ini_set('display_errors', 1);

Change it to:

  1. ini_set('display_errors', 1);

Increase PHP Memory Limit

If you encounter an error message that says “allowed memory size of x bytes exhausted (tried to allocate y bytes),” it may indicate a memory problem. To resolve this, you can increase the memory limit by including the following line in the command you are running:

-d memory_limit=XX

Example:

php -d memory_limit=4G bin/magento setup:di:compile

Check for updates

Make sure your Magento 2 installation is up to date. Run the following command to check for updates:

  1. composer update

Check for errors

Run the following command to see if there are any errors in your Magento 2 installation:

  1. php bin/magento setup:di:compile

If there are any errors, they will be displayed in the console. You may need to fix these errors before the commands work correctly.

Check if the command syntax is correct

Make sure you are using the correct command syntax. Refer to the Magento 2 documentation for the correct command syntax.

Please note: There could several other ways to resolve the issue. You may need further assistance from the Magento community or technical support.

How to Add Custom Magento 2 CLI Commands

Follow the steps below to add a custom console CLI command. This is useful for managing actions, indexes, modules, etc.

Step 1: Create a New Module For Custom CLI Comman

To begin, you can create a basic module named: Cloudways_Commandline in the app/code directory, adhering to the standard structure of VendorName/ModuleName. Make sure to include the necessary etc/module.xml and registration.php files in the root of the module’s directory.

You can check out our guide on how to create a simple module.

Step 2: Define the Command in di.xml File

Now, create a di.xml file in the etc directory of the module to define the command. Insert the following code in the file:

  1. <?xml version="1.0"?>
  2. <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  3. <type name="Magento\Framework\Console\CommandList">
  4. <arguments>
  5. <argument name="commands" xsi:type="array">
  6. <item name="CloudwaysHicustomer" xsi:type="object">Cloudways\Commandline\Console\Hicustomer</item>
  7. </argument>
  8. </arguments>
  9. </type>
  10. </config>

Where:

The <type> tag is pointing to the Magento\Framework\Console\CommandList class. Furthermore, it has the <argument> named commands and the <item> tag.

I have also declared a class Cloudways\Commandline\Console\Hicustomer in the <item> tag. This class will set the name and description of the command using the configure() method. The class will also define the execute() method for the command.

Step 3: Create Class for Magento 2 Console Command

Next, create the file Hicustomer.php (as defined in di.xml) in the directory Cloudways/Commandline/Console that extends Magento\Framework\Console\Command\Command class and copy the following code:

  1. <?php
  2. namespace Cloudways\Commandline\Console;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Input\InputOption;
  6. use Symfony\Component\Console\Output\OutputInterface;
  7. use Magento\Framework\Exception\LocalizedException;
  8. class Hicustomer extends Command
  9. {
  10. protected function configure()
  11. {
  12. $this->setName('cloudways:hicustomer');
  13. $this->setDescription('Demo command line');
  14. parent::configure();
  15. }
  16. /**
  17. * Execute the command
  18. *
  19. * @param InputInterface $input
  20. * @param OutputInterface $output
  21. *
  22. * @return int
  23. */
  24. protected function execute(InputInterface $input, OutputInterface $output)
  25. {
  26. $exitCode = 0;
  27. $output->writeln("Hi Customer");
  28. try {
  29. // throw new LocalizedException(__('An error occurred.'));
  30. } catch (LocalizedException $e) {
  31. $output->writeln(sprintf(
  32. '<error>%s</error>',
  33. $e->getMessage()
  34. ));
  35. $exitCode = 1;
  36. }
  37. return $exitCode;
  38. }
  39. }

The Hicustomer class has two methods:

  • The configure() method sets the command’s initial configuration (such as name, description, and arguments).
  • The execute() method will contain the logic executed when the Magento CLI command is called in the console.

Once the class has been declared, enable the module, run the setup upgrade command, and flush Magento 2 cache. Now, type the CLI command below to see the list of all available Magento 2 commands:

  1. php bin/magento list

You will notice that the custom Magento CLI command is also on the list.

Magento CLI Command 4

Now, run the php bin/magento cloudways:hicustomer command to see the desired result.

run-command-magento

Step 5 (Optional): Add Argument to Custom Magento 2 Command

Till step 4, we look at how to add a basic custom Magento CLI command. To make things interesting, I will demonstrate how to add an argument to the custom Magento command. For this, replace the current contents of the class file Hicustomer.php with the following:

  1. <?php
  2. namespace Cloudways\Commandline\Console;
  3. use Symfony\Component\Console\Command\Command;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Input\InputOption;
  6. use Symfony\Component\Console\Output\OutputInterface;
  7. use Magento\Framework\Exception\LocalizedException;
  8. class Hicustomer extends Command
  9. {
  10. private const NAME = 'name';
  11. protected function configure()
  12. {
  13. $this->setName('cloudways:hicustomer');
  14. $this->setDescription('Demo command line');
  15. $this->addOption(
  16. self::NAME,
  17. null,
  18. InputOption::VALUE_REQUIRED,
  19. 'Name'
  20. );
  21. parent::configure();
  22. }
  23. /**
  24. * Execute the command
  25. *
  26. * @param InputInterface $input
  27. * @param OutputInterface $output
  28. *
  29. * @return int
  30. */
  31. protected function execute(InputInterface $input, OutputInterface $output)
  32. {
  33. $exitCode = 0;
  34. if ($name = $input->getOption(self::NAME)) {
  35. $output->writeln('<info>Provided name is `' . $name . '`</info>');
  36. }
  37. else {
  38. $output->writeln("Hi Customer");
  39. }
  40. $output->writeln('<info>Success message.</info>');
  41. $output->writeln('<comment>Some comment.</comment>');
  42. try {
  43. // throw new LocalizedException(__('An error occurred.'));
  44. } catch (LocalizedException $e) {
  45. $output->writeln(sprintf(
  46. '<error>%s</error>',
  47. $e->getMessage()
  48. ));
  49. $exitCode = 1;
  50. }
  51. return $exitCode;
  52. }
  53. }

The Name argument for the custom Magento 2 command has been created and added to the configure() method. It can then be accessed in the execute() method.

Once again, run the setup upgrade command and flush the Magento 2 cache. Invoke the custom Magento CLI command using php bin/magento cloudways:hicustomer –Name=”ABC” and it will show “Hi ABC” as an output.

magento-run-custom-command

Final Words!

In conclusion, the Magento CLI may appear daunting, but once you grasp its workings, you’ll realize that you don’t have to be a developer to manage a Magento store. Especially if you’re using Cloudways managed hosting to host your Magento store.

I hope you found this tutorial on creating Magento CLI commands informative and helpful. It covered the basics and provided guidance on adding a new CLI command in Magento 2. If you have any feedback, comments, or questions, please don’t hesitate to let me know in the comments section below.

Stay tuned for more informative tutorials and tips to enhance your understanding of Magento and its features. Thank you for reading!

Post a Comment

0Comments
Post a Comment (0)
To Top