0

everyone. It's a little difficult to explain what I want to do.

I want to create a script 'example', which can input long commands for you after you run it with short parameters. For example,

$ example server # I input this line manually
$ ssh [email protected] # This line is automatically generated by the above command

So that I can edit the command line at the current line.

I am using shell ZSH. And I've tried something like history but failed at the end. Any suggestion?

2 Answers 2

1

I think it is not possible (or at least very hackish) to run an external script, so that anything is placed on the prompt for further editing

That being said, it is possible to extend zle (zsh's command line editor) with your own functions, so-called widgets.

Any user-defined widget has access to BUFFER, which contains the edit buffer and may also be modified.

Here a short prototype:

function example () {
    if [[ $BUFFER = 'server' ]]; then
        LBUFFER='ssh [email protected] '
    else
        zle accept-line
    fi
}

zle -N example
bindkey '^M' example

zle -N example creates a new widget named example and maps it to the function with the same name. bindkey '^M' example maps Control+M, also known as Return, to the widget example. So everytime you just type "server" and press Return it gets replaced by ssh [email protected] and the cursor is placed at the end for further editing, while any other line is executed/accepted as-is.

1

Instead of using a shell function, you can also use a keybinding. For example like that:

bindkey -s '\C-e\C-l' 'ssh [email protected]'

Here -s creates a string substitution, see man zshzle:

-s in-string out-string ... Bind each in-string to each out-string. When in-string is typed, out-string will be pushed back and treated as input to the line editor. When -R is also used, interpret the in-strings as ranges.

With the above example you can use CTRL+E,CTRL+L in insert ssh [email protected] into the command line at the current cursor position.

This has the advantage, that you can use this shortcut easily to construt a pipe, e.g.

cat foo | CTRL+E,CTRL+L  =>  cat foo | ssh [email protected]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .