Small victories - record and replay commands in terminal

The stupid trick that saves me tons of time while testing.

The problem

I work on a Mac all the time and spend much of my time in the terminal application.
When not editing the code using PHPStorm, Sublime Text or vim I will launch tests or some script using the terminal.
Much of my terminal bashing is to run tests using Codeception, PhpUnit and wp-browser.
One of the first tricks I’ve learnt to make my life less miserable using PHPUnit was to avoid running the cli command over and over:


aliasing the command in my shell configuration file:

alias t="phpunit"

to be able to run the PHPUnit tests simply typing t.
That’s fine for a start but when the test base grows I would like to run a smaller group of tests like:

phpunit tests/some/sub/folder

and be able to repeat that operation over and over until the issue in that specific group of tests is solved.
Should I set a new alias for something that I might use 20 times or so? I could but, I have to be sincere, I won’t do it.
With Codeception the tests could get even more complex like:

codecept run tests/unit/tad/WPBrowser/Extension/CopierTest.php -vvv


codecept run tests/unit/tad/WPBrowser/Extension/CopierTest.php:it_should_throw_if_source_file_does_not_exist -vvv

There is no way I will set aliases for each of these.

A solution

I’ve decided to tackle the issue and find a reliable and easy to remember solution.
I’m keeping general purpose aliases like t to run codecept run or phpunit and I’ve put in place some scripting in my shell configuration file (~/.zshrc being a zsh user) that allows me to record my last command and replay it.
The script is:

recordLast() {
    alias r="$(fc -ln -1)" 

alias rl=recordLast

The fc -ln -1 command returns the last command I’ve typed and that is aliased to the r.
The use flow is as simple as typing the long command I want to record and execute it one time and then record it:

codecept run tests/unit/tad/WPBrowser/Extension/CopierTest.php:it_should_throw_if_source_file_does_not_exist
codecept run tests/unit/tad/WPBrowser/Extension/CopierTest.php:it_should_throw_if_source_file_is_not_readable

from now on r will expand to codecept run ....
When I’m done I can record another command and replay it at will again having a good combination of time-saving and flexibility.