我正在尝试编写一个sudo !!与 Bash等效的函数。它有效,但仅当最后一个命令没有参数时。
到目前为止的功能是:
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
Run Code Online (Sandbox Code Playgroud)
测试相关行:
$ command sudo whoami
root
$ whoami
nick
$ command sudo (echo $history[1])
root
Run Code Online (Sandbox Code Playgroud)
到目前为止一切顺利,现在让我们尝试一个带有几个参数的命令:
$ 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
Run Code Online (Sandbox Code Playgroud)
嗯,奇怪。
使用 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
Run Code Online (Sandbox Code Playgroud)