1

Recently, I was getting a bit frustrated about not running commands as admin, and started using sudo !! a lot. I decided that, for ease of use, I'd create an alias ffs for that exact line. I added the following line...

alias ffs="sudo !!"

to my .zshrc.

However, when I tried using it, entering ffs into the terminal spat out an error:

sudo: !!: command not found

Why does the command not work when invoked using an alias? What can be used to fix this/instead of this to just rerun the previous command? Thanks in advance!

Dion
  • 113

1 Answers1

0

history expansion is not performed upon alias expansion.

Here to evaluate the same code as in the previous command but with sudo prepended to it and whatever you're passing as argument to the alias appended (bearing in mind that it will likely not do what you want with things like cmd1; cmd2 or for i (a b) echo $i), you'd do:

alias ffs='eval "sudo ${history[@]:0:1}"'

Or you could have it run sudo zsh -c <the-code-from-the-previous-command+your-args-appended>, but then again, it won't work for things like echo $non_exported_variable

ffs() sudo zsh -c "${history[@]:0:1} ${(j[ ])@}"

The $history special associative array maps history event numbers to the corresponding command line. It's also special in that it expands from the newest to oldest, so above we can get the most recent event by getting the first in the entry in its list of values here using ksh93-style ${array[@]:offset:length} though you could also use ${${history[@]}[1]}.

Alternatively, you could use $(fc -nl -1) though that would mean forking an extra process.