by unfletch · 13y ago · 0 comments
'!!:n' selects the nth argument of the last command, and '!$' the last arg
A lot of people know about "!$" (which is shorthand for !!:$), but that's just the tip of Bash's history expansion. I use these things all the time. One of my favorite keystroke savers is adding :h, the head modifier, to !$. For example: $ cp file.txt /some/annoyingly/deep/target/directory/other.txt
$ cd !$:h
$ pwd # => /some/annoyingly/deep/target/directory
Once you understand how each component works it's easier to put them together into new (to you) combinations. For example, once you know that !$ is shorthand for !!:$, it's not a huge leap to reason out that you can use !-2:$ to get the last argument to the 2nd-to-last command. Or !ls:$ for the last arg to the most recent `ls` command.I also prefer to do substitution with the :s modifier rather than ^ as suggested at the link, for consistency's sake:
$ echo "foo bar"
foo bar
$ echo !!:s/bar/baz
foo baz
$ echo !?bar?:s/foo/qux
qux bar
Relevant Bash manual pages:http://www.gnu.org/software/bash/manual/html_node/Event-Desi...
http://www.gnu.org/software/bash/manual/html_node/Word-Desig...
http://www.gnu.org/software/bash/manual/html_node/Modifiers....
$ echo a b c d
a b c d
$ echo !!:2:p
echo b
$ echo !!:2
-bash: :2: bad word specifier # there was only 1 argument in last command
However: $ echo a b c d
a b c d
$ echo !!:2:p
echo b
$
<up-arrow pressed once will give the following prompt>
$ echo b $if Bash
Space: magic-space
$endif
Basically does the same thing as :p, but after a space instead of enter.Edit: fixed formatting.
$ cp file.txt /some/annoyingly/deep/target/directory/other.txt
$ cd then press Alt + .
$ pwd # => /some/annoyingly/deep/target/directory $ echo foo/bar
foo/bar
$ echo !$ !$:h
foo/bar fooIn comparison. !$:h understands its task at a higher level. And thanks to key rollover, typing different characters, like !$:h, is quicker than tapping away at . until visual feedback, which may lag, tells me I've done enough.
$ echo "foo foo"
foo foo
$ echo !!:s/foo/bar
echo echo "bar foo"
echo bar foo
$ echo "foo foo"
foo foo
$ echo !!:gs/foo/bar
echo echo "bar bar"
echo bar bar $ !!
runs the previous command.This is especially useful:
$ !!
$ sudo !!$ cp file.txt /some/annoyingly/deep/target/directory/other.txt
$ cd !$ (No such file or directory)
(up arrow and then backspace to directory)