Ari Sweedler Ari Sweedler - 1 year ago 63
Bash Question

What's the use of `!#` in bash?

I'm not talking about the UNIX shebang meant to give the path of an interpreter. In fact, the shebang has made it quite hard to google this question successfully...

I'm talking about


  • !!
    retrieves the immediately preceding command (akin to the up arrow, but more usable)

  • !$
    retrieves the last word of the last command

  • !#
    appears to retrieve the current line

But what're actually useful uses of

  • echo !#
    expands to
    echo echo

  • echo echo !#
    expands to
    echo echo echo echo

  • ls !#
    expands to
    ls ls

All of which seem overwhelmingly pointless. All I know about the
command is what I've learned from using it – I'm not certain that I know its true functionality.

Answer Source

As mentioned in 2 comments and 1 answer, you can easily find the section of man bash:

!#     The entire command line typed so far.

What isn't made explicit by the man pages or other documentation and perhaps leading you your bafflement to a useful use for !# is that bash even designators are meant to be used in combination with the word designators and modifiers (found just below event designators on the man page). The use cases also make more sense when chaining commands together with pipes, ; or &/&&

For example:

I could use the substitution modifier to run a script against two inputs bar and baz:

$ ./ bar; !#:s/bar/baz/

expands to form:

./ bar; ./ baz;

Or an example from the Docs (R.I.P. Docs) reproduced below shows how to use the word selector :N to select the first argument to the command as typed so far and neatly cd into the just created directory:

$ mkdir backup_download_directory && cd !#:1
mkdir backup_download_directory && cd backup_download_directory

These examples are pretty trivial, but I hope they show how !# could really save somebody some serious redundant typing while crafting powerful one-liners.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download