ISO27001:2013
Certified Supplier

FIND OUT MORE

We're an ISO27001:2013 Certified Supplier

blog-post-featured-image

Sometimes we want to use the results of the previous bash command in the next.  For example, let’s say we’re clearing out some old text files. We start by listing them:

$ ls *txt
info.txt mynotes.txt puppynames.txt techmeeting.txt

Of course this is a contrived example: with only four files listed, the “shortcut” below takes longer than just deleting the files you don’t want. But you knew that, right?

We realise we want to keep the the last file, techmeeting.txt, so we build a command that will just list the files we want to delete:

$ ls *txt|grep -v techmeeting.txt
info.txt
mynotes.txt
puppynames.txt

In reality, we may well make this line more complex so that it lists only the files we want to delete.

What I used to do next was recall the last command, and then edit it like this:

$ rm $(*txt|grep -v techmeeting.txt)

The $(*txt|grep -v techmeeting.txt) construct is replace by the output of the  command(s) between the parentheses, and so becomes:

$ rm info.txt mynotes.txt puppynames.txt

That works, but there’s a quicker way. At the shell, !! is replaced by the previous command, so we can just type:

$ rm $(!!)

Could this Linux Tip be improved?

Let us know in the comments below.

3 thoughts on “Linux Tips: Using Results of the Previous Command”

Leave a Reply

Your email address will not be published. Required fields are marked *