2

I have a somewhat idiosyncratic CLI workflow, but it works for me. I commonly iterate on commands and then use the result of those commands in the next command. For example:

Finding a file:

$ ff thing_im_looking_for_spec
./specs/foo/bar/thing_im_looking_for_spec.rb

Re-running that command (since it's fast) and using it's result as an argument to another program:

$ rspec `!!`

...which expands to:

$ rspec `ff thing_im_looking_for_spec`

...and runs the test I'm looking for. From there I can press the up arrow and make a quick edit to:

$ vim `ff thing_im_looking_for_spec`

...to edit that file.

I know it's weird, but it works great. It's very comfortable for me to use [backtick][bang][bang][backtick] to mean "yeah, that thing."

But "`!!`" is just a wee bit hard to type. Is it possible to make an alias for it? I've had trouble figuring out how to do this because "`!!`" is itself an alias for the last command.

New contributor
Ellsworth Kelly is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1

The !! itself can be wrapped in an alias or a function by using history -p, which allows scripts to get the result of any !expansion (even if the whole feature is disabled):

alias 1='eval "$(history -p !!)"'

Now it's vim `1` or rspec `1`, which is relatively more convenient to type (no need for Shift). Can't do much about the backticks, however.


Well, technically you can achieve this without backticks, but it involves weird tricks:

shopt -s extdebug
trap 'case $BASH_COMMAND in *" that")
          eval "${BASH_COMMAND/%" that"/" $(eval "$(history -p !!)")"}";
          false;
      esac' DEBUG

Now it's vim that or rspec that. (This example only detects the last word, to limit the explosion risk. Modifying to match/replace words anywhere in the command line is left as an exercise.)


One less weird trick is to bind a keypress (macro) that automatically inserts `!!` as if typed:

bind '"\e[2~": "`!!`"'

This example tells bash's readline to translate \e[2~ (which is actually the Insert key) to `!!`, so you can type vim Insert to obtain vim `!!`. Any input, not necessarily a special key sequence, can be turned into a macro.

(Among other possible convenient keys, Alt+Enter is \e\n, Ctrl+F is \C-f, and so on.)

  • Wow, this is so cool. Binding [Insert] seems to strike the nicest balance between convenient vs. crazy. Thank you. – Ellsworth Kelly Jul 12 at 18:10

Your Answer

Ellsworth Kelly is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.