Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interactively expand a bang command in bash?

Tags:

bash

shell

zsh

Shells like zsh and bash have bang commands which start with an exclamation mark and expand to items in the user's history.

To get the last argument of the the last command that was run, one can use !$, e.g.

$ echo one two three
$ echo !$ !$ !$
> three three three

In zsh, it is possible to expand these bang commands interactively:

touch foo bar
ls !$<TAB>

!$ will be expanded to foo inline.

This is very useful because it often prevented me from mistakes: I press tab to expand and make sure I got it right and C-/ to undo the expansion when I'm confident.

Is there a setting in bash to achieve interactive expansion of bang commands?

What about expansion of subshells and general variables for that matter (i.e. echo $(uname)<TAB> to echo Linux and echo $SHELL<TAB> to echo /bin/bash).

like image 876
kba Avatar asked Oct 30 '15 10:10

kba


People also ask

How do I expand in bash?

Command substitution. Bash performs the expansion by executing COMMAND and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.

What is !$ In bash?

!!:$ designates the last argument of the preceding command. This may be shortened to !$ .

What does $! Mean in Linux?

Meaning. $! $! bash script parameter is used to reference the process ID of the most recently executed command in background.

Which command in bash executes the last line in the shell history that starts with LS?

!- 1 is the same as !! and executes the last command from the history list, !- 2 second to last, and so on. Another way to search through the command history is by pressing Ctrl-R .


1 Answers

There are a few options you can use for history expansion. One is the :p modifier, which prints the expanded command instead of executing it.

$ echo foo
$ !!:p
echo foo

Another is to use the histverify option, which puts the result of history expansion in the shell buffer for editing instead of immediately executing it.

$ shopt -s histverify
$ echo foo
foo
$ !!
$ echo foo

If you're happy with the command, simply hit Enter again to execute it, as if you had just typed it.

By default, the Readline command history-expand-line is bound to M-^ (Alt-^ or Esc-^, depending on what your terminal emulator sends as the meta key), which expands any history expansions on the current command line.

There is also a general Readline command shell-expand-line (bound to M-C-e by default), which expands everything on the command line, just as the shell would after hitting Enter but just before actually executing it.

like image 71
chepner Avatar answered Oct 17 '22 18:10

chepner