Search code examples
fish

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


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.


Solution

  • 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