Rajdeep
Rajdeep

Reputation: 2472

How to bind previous and next history keys to control j and k in bash?

I've been trying to figure out a way to bind previous-history to Control k and next history to Control j in bash. I am aware that there are already bindings like Control p and n for these commands but the thing is I have gotten used to Control k and j. I binded them when I was using vim in zsh.

I now need to ssh into a server (which uses bash) for a project and would like to have the same key bindings. I have tried to include these commands in my .inputrc:

"C-k": previous-history
"C-j": next-history 

However it is showing this error when the file is loaded on login.

-bash: C-k:: command not found
-bash: C-j:: command not found

Besides C-k and C-j I also tried using ^k and ^j as well but it did not work.

Some context: I use a Macbook and these were the bindings that worked for zsh:

# For Control k and j
bindkey '^k' up-line-or-history
bindkey '^j' down-line-or-history

UPDATE: Also I added . ~/.inputrc in my .bash_profile for it to run during ssh login.

Upvotes: 0

Views: 1047

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52336

In the Readline init file, ~/.inputrc, there are two ways to use keybindings (see manual):

  • Keynames:

    Control-k: previous-history
    Control-j: next-history
    
  • A keyseq: this has to be placed in double quotes and recognizes some GNU Emacs style escapes, notably \C for Ctrl:

    "\C-k": previous-history
    "\C-j": next-history
    

Also, you can't treat ~/.inputrc as a Bash script (like sourcing it from a shell initialization file); it is read by whichever program uses the Readline library – Bash, in your case.

You can reload it with re-read-init-file, which is bound to C-x C-r by default.

Upvotes: 1

Related Questions