Everybody knows about using !! to add sudo to your previous command, but there are a couple other things I constantly use it for. So this is just a little PSA in case it never occured to you:

1. grep results

Say I want to search a bunch of files for a string, and then open all files containing that string in my editor.

I want to check the search results first, and I never get the exact search correct on my first try anyway, so I’ll run a series of commands that might look like…

grep -rn . -e "mystring"
...
grep -rn . -e "my.\?string"
...
grep -Rni . -e "my.\?string"
...

Checking the results each time, until I have exactly the set of files that I want.

Here’s the trick: now add the “-l” flag to grep to get just the file paths:

grep -Rnil . -e "my.\?string"

Now when you use !!, you’ll get all those filenames. Therefore we can just do vim -p $(!!) to get all those files opened in tabs in vim.

2. with which

Sometimes I want to read or edit a script that’s on my computer.

To find it, I run which some-command. This confirms that it exists under that name, and that it’s an actual script and not an alias or shell function.

Now, we can just use vim $(!!) or cat $(!!) or whatever to open it.

OC by @[email protected]

  • Zachariah
    link
    fedilink
    English
    arrow-up
    1
    ·
    8 months ago

    Is this the same !! or just a coincidence that the same symbols are used?

    • da_cow (she/her)@feddit.org
      link
      fedilink
      English
      arrow-up
      2
      ·
      3 months ago

      It should be a little bit different. In this example the $(!!) in the vim command means, that the last command gets executed again, the output gets captured and passed as arguments to vim to open the files. If you ever typed a command, but forgot to add sudo to it, you can reexecute the command with root privileges by typing sudo !! into your shell. This should be the syntax shown here.