How to get previous command without arrow key

Usually we can use the upwards arrow key to get the previous command. But that does not always work, it can happen that you get the ASCII sequence instead (“^[[A…”) but I also wonder if there was this functionality at older keyboards which did not have the arrow key, how did it work in those days?

Is or was there another way?

In emacs mode, CtrlP (previous), other direction is CtrlN (next)

in vi mode, ESC (to go to command mode) and k for going up and j for going down

Answered By: Philippos

You can do it with two exclamation marks, in your shell just: !!

Answered By: echo6667

Just type history in your favourite shell will trig the dump of your whole history.

You can also try ctrl-r + typing the first characters of the searched command…

Answered By: binarym

Depends on the shell, but here are some methods:

  • !!
  • Ctrl + P
  • !-1

All have to be commited with a press of Enter

Answered By: Robert Riedl

As said, it depends on the shell, but in addition to these answers, another way:

The history command will show some output like this:

   89  bash --version
   90  source /Library//Developer/CommandLineTools/usr/share/git-core/git-completion.bash
   91  brew install bash-completion
   92  source ~/.bashrc

And then you can do for example

!89 to re-run the command (bash --version in this case)

Answered By: ChatterOne

There are several layers in which you can ask for the last command.

Line editor

The line editor (where you type your commands) is provided directly by ksh, by the library readline in bash, and by the library zle in zsh. Other shells, like dash may not have an editing library to understand this keys (unless compiled with the --with-libedit option enabled) .

This work in ksh, bash, zsh:

CtrlP # Emacs mode (previous)
CtrlN # Emacs mode (next)
ESCk # vi mode ESC to go to command mode and k for up
ESCj # vi mode ESC to go to command mode and j for down

history

The history system provided by many shells allow the expansion of some shortcuts:

!!    # bash and zsh, may be provided by `alias !!='fc -e -'` in ksh.
!-1   # bash and zsh only

commands

There are some commands which are able to retrieve history commands.

Like the quite verbose command (only to print):

history 2 | head -n-1

or the older and therefore usually more portable fc command (directly re-executes):

fc -e - -1

Or maybe the simpler fc -s -1, but zsh doesn’t accept such option for fc.

If you want to only print the command, use: fc -nl -1 -1.

To edit, set FCEDIT to a text editor (ex, ed, emacs, vi, etc.) and use fc directly: fc -1.

Answered By: user232326
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.