Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 user@192.168.1.2 # 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?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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 user@192.168.1.2 '
    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 user@192.168.1.2 and the cursor is placed at the end for further editing, while any other line is executed/accepted as-is.

share|improve this answer

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

bindkey -s '\C-e\C-l' 'ssh user@192.168.1.2'

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 user@192.168.1.2 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 user@192.168.1.2

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.