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

StackOverflow https://stackoverflow.com/questions/22650715

  •  21-06-2023
  •  | 
  •  

Pergunta

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.

Foi útil?

Solução

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

Outras dicas

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 
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top