Skip to content

A time-saving way to re-run a range of terminal commands

Yesterday, I wrote about the Z shell’s built-in r and how to recreate it in Bash with the fc command. Today, I have some bonus knowledge for you.

In addition to re-running a single command from your history, the command r can also be used to conveniently run multiple commands again.

Introducing the optional second argument#

To learn about running r with no or just one argument, read the previous article. By providing an optional second argument, you can select a range of commands from your history that you want to execute again. That way, you won’t re-run just a single command from your history but multiple (subsequent) commands.

If you execute the command history, you’ll see something like this:

…
189   echo "Going to update some Python packages."
190   pip install --upgrade black
191   pip install --upgrade isort
192   pip install --upgrade mypy
193   echo "Done for now with updating Python packages."
…

You can refer to the individual commands in your history by their numeric identifiers (here: 189, 190, 191, and so on).

If you wanted to execute the shown three commands for updating your Python packages another time, I’m sure you’d already know convenient ways to do that. But we can also put the command r to use, now that we know about it.

Selecting a range of commands by their numeric identifiers#

The command r accepts two of these identifiers: one for the start and one for the end of the range. For example:

r 190 192

That r command achieves the same results as manually re-running these commands:

pip install --upgrade black
pip install --upgrade isort
pip install --upgrade mypy

The command selected by the second argument (here: 192) will be included in the range, which is different from how ranges work in Python.

Now you even have some bonus knowledge. 🙂

Selecting the n previous commands with negative indices#

You can also use negative numbers (where -1 represents the last command) to re-run, say, the last five commands:

r -5 -1

Mixing the types of arguments#

You can also mix the arguments to, for example, re-run every command you ran since you last executed a command that begins with pip:

r pip -1

I don’t know how useful the following tip is, but you could also re-run every command between the time you last executed a pip command and the time you last ran an echo command:

r pip echo

Final words#

Today I learned that, with the built-in r, I can re-run not just single commands individually but also ranges of commands (for example, the last three commands). Hopefully, you could learn something from this post too. In any case, be well.

Buy Me A Coffee

Comments