11

In the Terminal I can use !! which will reference my previous command.
Is it possible to use this in an alias? I have tried it, but what happens is that the double exclamation marks are interpreted literally.

What I want to have possible is:

  1. I enter some command
  2. I type an alias that will include what was entered in step 1

If there is a solution using scripts that is also acceptable.

5
  • what is your main goal ? add more options to last command ? Jul 19, 2016 at 12:14
  • No my goal is to quickly type a long command I often use. In the middle of it is a long string that often is the previous command Jul 19, 2016 at 12:19
  • it seems you want just fc command so it opens a text editor , because that is the easiest way to edit long commands. Let me add it to my post . Also , maybe you could provide an example of command ? Jul 19, 2016 at 12:31
  • Added an edit to my post Jul 19, 2016 at 12:35
  • superuser.com/q/240180/337511 Jul 19, 2016 at 15:27

3 Answers 3

11

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.

9

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.

1
  • So this will allow me to add something to the beginning of my last command. What about in the middle of it? Jul 19, 2016 at 12:24
8

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .