Ben Keil
Ben Keil

Reputation: 1183

Set and execute a command from a function

How can I write a fish function that executes a command in a string and make it appear in the history?

function qh --description 'Use peco to query command history'
    if test (count $argv) = 0
        set peco_flags --layout=bottom-up
    else
        set peco_flags --layout=bottom-up --query "$argv"
    end

    history | peco $peco_flags | read cmd

    if test $cmd
        commandline $cmd
    else
        commandline ''
    end
end

This does not work...

Upvotes: 0

Views: 1192

Answers (1)

ridiculous_fish
ridiculous_fish

Reputation: 18551

It is possible to create a key binding which sets the command line and then executes it; that command will then appear in history. Example:

function whatday
    commandline "echo Today is $(date +%A)"
    commandline -f execute
end
bind \eq whatday

now alt-q will set the commandline to echo Today is Sunday and execute it; it appears in history.

Beyond that there are also abbreviations which allow replacing tokens with text; but the text is just static (e.g. gco -> git checkout).

There is as yet no way for an arbitrary fish function (e.g. run as part of a shell script) to append to history, only delete and read from it.

Upvotes: 2

Related Questions