我正在尝试编写一个在Bash中相当于sudo !!
的函数。它可以工作,但只有当最后一个命令没有参数时才会有效。
到目前为止,功能是:
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
测试相关行:
$ command sudo whoami
root
$ whoami
nick
$ command sudo (echo $history[1])
root
到目前为止一切顺利,现在让我们尝试一些带有几个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
嗯,奇怪。
答案 0 :(得分:4)
我和你有同样的问题,我使用oh-my-fish
修复了它
(它是fish
shell的插件管理员)https://github.com/oh-my-fish/oh-my-fish。您可以使用以下命令安装它:
curl -L https://get.oh-my.fish | fish
然后使用以下命令安装插件bang-bang
(以允许!!
和!$
):
omf install bang-bang
答案 1 :(得分:3)
使用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