Working faster with bin/magento

The bin/magento command is the entry point to working with Magento 2's command line tasks. Prompted by a couple of recent tweets I thought I quickly write down a couple of tips to speed up working with it.

First up, depending on how your system is configured, you are either able to use bin/magento directly or you need to type php -f bin/magento (or even something like php70 -f bin/magento if you have multiple versions of php running at the same time). This gets rather cumbersome to type out all the time...

Enter command aliases.

You can provide an alias to any command simply by running:

alias m2='bin/magento'

(or whatever else command you need to run - see above).

Now instead of typing out bin/magento all the time we can just type m2 followed by whatever task we want to execute, so for example m2 cache:clear. Read more on aliases for example here to make this permanent by adding this to your ~/.bashrc file.

We can take this a step further as well. The bin/magento command only works when executed from the root directory of your site. We can switch to this folder as part of the aliased command:

alias m2='cd /var/www && bin/magento' 

Now we can type m2 from anywhere and it will take us to the Magento 2 folder as the first step and then runs the Magento command.

There is one further improvement we can make. It is important to not mix up different levels of permissions as that can break things. To avoid the bin/magento command being run with a different user to the one owning the file we add an additional safe guard via an if clause:

alias m2='cd /var/www && if [ `whoami` == `stat -c '%U' bin/magento` ]; then bin/magento "$@"; else echo "bin/magento should be run as user `stat -c '%U' bin/magento`";fi'

Next the task arguments after bin/magento can all be shortened as well. So instead of typing out bin/magento cache:clean you can just use bin/magento c:c. You can abbreviate any task like this. However you might come across an error message like:

$:/var/www$ bin/magento i:r

  Command "i:r" is ambiguous (indexer:reindex, indexer:reset).

in the above case we abbreviated too much and the system can't determine if we wanted to use indexer:reindex or indexer:reset. So we need to make sure that it can differentiate between the two by either using $:/var/www$ bin/magento i:rei or $:/var/www$ bin/magento i:res.

The alias can be combined with the shortened arguments as well which adds up to quite a few less characters to type:

php -f bin/magento cache:clean
m2 c:c

Instead of using abbreviations you can also use command completion instead of typing out every task you can hit [TAB]. Please see the project here.

Kristof Ringleff

Kristof Ringleff

Founder and Lead Developer at Fooman

Join the Fooman Community

We send our popular Fooman Developer Monthly email with Magento news, articles & developer tips, as well as occasional Fooman extension updates.