How to use Xdebug and PHPStorm to fix problematic Magento CLI commands

In PHPStorm navigate to Run -> Edit Configurations… and add a new PHP Script.

As a File use your project’s path to bin/magento
As Arguments input command you wish to debug, for example: setup:upgrade --keep-generated
Lastly, set your IDE key through environment variables: XDEBUG_CONFIG="idekey=PHPSTORM"

Do note that it won’t work if Xdebug is disabled or is not installed.
Check if it’s on by running php -v.
If it’s enabled, you will see something like this:

PHP 7.4.27 (cli) (built: Dec 20 2021 21:28:15) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies
    with Xdebug v3.1.2, Copyright (c) 2002-2021, by Derick Rethans

If it’s disabled, the Xdebug line won’t be there:

PHP 7.4.27 (cli) (built: Dec 20 2021 21:28:15) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies

sudo phpenmod xdebug to enable it
sudo phpdismod xdebug to disable it

You should also restart your webserver:
sudo service apache2 restart if you are using Apache
sudo service nginx restart if you are using Nginx

I moved those enabling/disabling steps into .bashrc file to make toggling between Xdebug a little bit faster. You can find it here.

Full working example:

Click to zoom

You can test it by setting up a breakpoint here.

Run it by navigating to Run -> Run… and selecting the name that you used when setting everything up (in my case this is bin/magento setup:upgrade)

Step 2 – console tab appears

Click to zoom

Voilà! Xdebug breakpoint got triggered

Click to zoom

Happy debugging adventurer.