Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running last command with sudo in fish only works if it has no arguments?

Tags:

fish

I'm trying to write a function that does the equivalent of sudo !! in Bash. It works, but only when the last command has no arguments.

So far the function is:

function s --description "Run last command (or specified command) using sudo"
    if test $argv
        switch $argv[1]
            case '!!'
                command sudo (echo $history[1])
            case '*'
                command sudo $argv
        end
    else
        command sudo fish
    end
end

Testing the relevant line:

$ command sudo whoami
root
$ whoami
nick
$ command sudo (echo $history[1])
root

So far so good, now lets try a command with a few args:

$ echo hi >> /etc/motd
An error occurred while redirecting file '/etc/motd'
open: Permission denied
$ command sudo (echo $history[1])
sudo: echo hi >> /etc/motd: command not found

Hmm, strange.

like image 585
Nick Sweeting Avatar asked Mar 26 '14 03:03

Nick Sweeting


2 Answers

Got it working using eval.

function sudo --description 'Run command using sudo (use !! for last command)'
      if test (count $argv) -gt 0
          switch $argv[1]
              case '!!'
                  if test (count $argv) -gt 1
                      set cmd "command sudo $history[1] $argv[2..-1]"
                  else
                      set cmd "command sudo $history[1]"
                  end
              case '*'
                  set cmd "command sudo $argv"
          end
      else
          set cmd "command sudo fish"
      end
      eval $cmd
  end
like image 68
Nick Sweeting Avatar answered Sep 20 '22 10:09

Nick Sweeting


I had the same problem as you, and I fixed it by using oh-my-fish (it's a plugin manager for fish shell) https://github.com/oh-my-fish/oh-my-fish. You can install it with this command :

curl -L https://get.oh-my.fish | fish

Then install the plugin bang-bang (to allow !! and !$) with this command :

omf install bang-bang 
like image 24
Sidahmed Avatar answered Sep 22 '22 10:09

Sidahmed