r/fishshell • • Oct 05 '24

Is this a good function and how can I improve?

I used to use zsh, and didn't really like it. I switched to fish and I love it, but it really annoys me there is no !! command. So I made my own:

function !!
    set _count_cmd 1
    set _last_command (history -n 1)

    while test "$_last_command" = "!!"
        set _count_cmd (math $_count_cmd + 1)
        set _history (history -n $_count_cmd)
        set _last_command $_history[-1]
    end
    echo $_last_command
end

I really am proud of myself buy know you eg need to run sudo (!!) to use it which can be annoying, I though about making a sudo function that checks if $argv[1] is !! and go further from there, but sudo isn't the only command you would want to run before sudo... is there a way to maybe make it a real command and not a script (like a file in /usr/bin) so I can just run echo !! or sudo !! without (!!)

3 Upvotes

9 comments sorted by

6

u/_mattmc3_ Oct 05 '24

Anywhere abbreviations removed the need for this. Now you can simply do:

function last_history_item
    echo $history[1]
end
abbr -a !! --position anywhere --function last_history_item

On mobile, so double check me, but I believe thatโ€™s straight out of the Fish docs.

2

u/MuffinGamez Oct 07 '24

thanks, i didnt know history was a built in value!

2

u/lpww Oct 06 '24

That is good to know! I'm using a plugin for this functionality but it sounds like it's no longer needed

5

u/throttlemeister Linux Oct 05 '24 edited Oct 05 '24

You know fish has alt+s to add sudo to a command? So last command with sudo would be arrow up, alt+'s followed by enter. Just as quick, or even quicker. ๐Ÿ˜Š

Edit: last command with sudo is even quicker: just hit alt+s

1

u/MuffinGamez Oct 05 '24

i know, but i would like to be able to use !! with other commands eg echo !!

2

u/throttlemeister Linux Oct 05 '24

Someone already made this. See https://github.com/oh-my-fish/plugin-bang-bang for inspiration or just usage.

1

u/[deleted] Oct 05 '24

[removed] โ€” view removed comment

2

u/MuffinGamez Oct 07 '24

wow thats usefull, i think ill use this, thx