This recipe applies to a scenario in which we have collected a series of commands that we want to run on a file.
We can run them using bash, but in this case, we want to check the output of each command. It’s also possible that some of them fail, and we want to be able to run it again or test it later.
In this example, we have a series of aptitude commands for downgrading versions of certain packages that we might have accidentally installed.
An extract of this file would be something like this:
Through ViM, ‘s features, we can facilitate and semi-automate the running task, always having control of each command’s results and the option to act, if there’s the case.
What are we going to use?
- Macro creation and editing
- Running commands from within the same editor
- The act, repeat, reverse mantra[1]
Preparation
What we are going to do is recording a macro which consists of deleting the line where the cursor is located and using the log where the deletion is kept to run the command.
Next, the ViM commands for preparing the macro.
They should be run from normal mode and without any space (in this case, it has been broken down for clarity):
The run could include some interaction with the user (click Y, or <CR>, or something similar), which is also recorded on the macro. When we return from the run output, we will press ‘q’ again to stop the macro recording. If we have interacted in the shell, we will have to remove the corresponding keys from the macro, and we can do it by editing the log ‘q’, where it has been recorded.
To do so from normal mode, we will copy the macro content in an alternative buffer (or at the end of the same file), we will edit it as if it was a normal text, and we will save the content on the same log again.
We should have a similar line to this one:
We simply delete the one we don’t want to be included in the macro and we save the line on the ‘q’ log again (deleting it from the file as well):
First run
The first time we run it, we will do it as @q (indicating the q log where we have recorded the macro). It will carry out the run and we will be able to interact with the run command (in this case, aptitude). The run also includes line deletion, so we will be automatically emptying the buffer with the pending commands.
If any of the commands don’t work correctly (or in the case of aptitude, hay problemas de dependencias y queremos dejar su resolución para más adelante), we can always recover the previous line content (it has been saved in the logs by default, the “0” and ‘“’ due to deletion through “dd“).
Run repetition for the rest of the lines
Once we verify the macro works correctly, we can repeat it through ‘@@’, which repeats the last macro run (quicker and more convenient than @q).
It can also be automated to run on each line of the file, but in this case, we are interested in monitoring all runs.
Comments