Can I use '!!' in aliases or scripts?

Solution 1:

The command that lists the last executed command is fc -nl -1 . Using output substitution , we can add more parameters to the same content

$> ls /etc/passwd
/etc/passwd
$> $(fc -nl -1)  /etc/group                                                     
/etc/group  /etc/passwd
$> 

Quoting , however, may be an issue with this approach

A very nice feature of fc is that if you just run fc command by itself, it will open text editor specified inFCEDIT variable (which you probably want stored in ~/.bashrc) and the contents of the line will be your last command. For your ease, I suggest you use nano as your text editor, but if you know vim - even better.

For example, what if I need to edit qdbus org.ayatana.bamf /org/ayatana/bamf/matcher org.ayatana.bamf.matcher.ActiveWindow Huge line, right ? But with fc, I can open vim and edit /org/ayatana/bamf/matcher , save, exit and it will run.

Solution 2:

You can't use !! but ...

From the manual:

A useful alias to use with the fc command is r='fc -s', so that typing ‘r cc’ runs the last command beginning with cc and typing ‘r’ re-executes the last command.

Solution 3:

If you insist on using the !! history expansion syntax instead of fc (mentioned already), there is a way.

By default, history expansion is disabled for non-interactive shell sessions e.g. in scripts.

To enable history expansion in scripts enable the relevant shell options first:

set -o history 
set -o histexpand

set -o histexpand can be written as set -H too.

Now the history expansion operations e.g. !! would work inside the script.