Bash history substitution trick

I saw the following neat little trick in this link:

# renaming a long file-name using a regex
$ touch config.txt
$ mv config.txt !#:1:s/txt/json

The exact meaning of the !# is, quoting from the man page:

Event Designators       An event designator is a reference to a command line entry in the history list.  Unless the reference is absolute, events are relative to the current position in the history list.
       !      Start a history substitution, except when followed by a blank, newline, carriage return, = or ( (when the extglob shell option is enabled using the shopt builtin). 

<snipped>

 !#     The entire command line typed so far.

From ‘man bash’

i.e. most people know that bash can insert things from history using commands like !! and !50 (i.e. rerun last command and rerun the 50th history item respectively).

But !# let’s you take something from the existing line and re-use it.

Here is another example, from here:

curl http://beyondgrep.com/ack-2.14-single-file > ~/bin/ack && chmod 0755 !#:3 

In this case, !#:3 takes the 3rd element from the existing command. Starting from zero, that turns out to be ~/bin/ack in this case.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s