TL;DR: alias @@='$($(fc -ln -1) |& tail -1)'
Bash's history interaction facilities don't offer any mechanism to examine the output of commands. The shell doesn't store that, and history expansion is specifically for commands you have yourself run, or parts of those commands.
This leaves the approach of rerunning the last command and piping both stdout and stderr (|&
) into a command substitution. heemayl's answer achieves this, but cannot be used in an an alias because the shell performs history expansion before expanding aliases, and not after.
I can't get history expansion to work in a shell function either, even by enabling it in the function with set -H
. I suspect !!
in a function will never be expanded, and I'm not sure what it would be expanded to if it were, but right now I'm not sure precisely why it isn't.
Therefore, if you want to set things up so you can do this with very little typing, you should use the fc
shell builtin instead of history expansion to extract the last command from the history. This has the additional advantage that it works even when history expansion is disabled.
As shown in Gordon Davisson's answer to Creating an alias containing bash history expansion (on Super User), $(fc -ln -1)
simulates !!
. Plugging this in for !!
in heemayl's command $(!! |& tail -1)
yields:
$($(fc -ln -1) |& tail -1)
This works like $(!! |& tail -1)
but can go in an alias definition:
alias @@='$($(fc -ln -1) |& tail -1)'
After you run that definition, or put it in .bash_aliases
or .bashrc
and start a new shell, you can simply type @@
(or whatever you named the alias) to attempt to execute the last line of output from the last command.
ek@Io:~$ alias @@='$($(fc -ln -1) |& tail -1)'
ek@Io:~$ evolution
The program 'evolution' is currently not installed. You can install it by typing:
sudo apt-get install evolution
ek@Io:~$ @@
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
evolution-common evolution-data-server evolution-data-server-online-accounts
....
command_not_found_handle
shell function or a script it runs (usually just/usr/lib/command-not-found
). I think you could make it so you're prompted interactively with the option to automatically install the package, or (probably better) so that the name of the package is stored somewhere and can be installed by running a short command. That's different enough from what you've asked here, you might consider posting a separate question about it. – Eliah Kagan May 10 '15 at 14:57