Viewing Session History in the bash Shell

Viewing Session History in the bash Shell

Another cool feature of the bash shell is that it lets you easily reuse commands from your session history, which shows you the list of commands you've used during a session or in previous sessions (Code Listing 3.9). Viewing history is handy for reviewing your Unix session, using previous commands again (rather than retyping them), and modifying (rather than completely retyping) complex commands.

Code Listing 3.9. In this example, we typed the first command, then pressed to reuse the previous ls command. !40 recycled the 40th command from the listing.

[ejr@hobbes clean]$ ls background.htm  info.htm     logo.gif [ejr@hobbes clean]$ ls background.htm  info.htm      logo.gif [ejr@hobbes clean]$ history    1  free    2  id deb    3  id ejr    4  uname -a    5  ls ...   40  cd   41  cp .bash_history oldhistory   42  vi .bash_history   43  elm   44  ls -la   45  ls -la .e*   46  elm   47  lynx   48  history   49  vi .bash*his*   50  history   51  cd clean   52  ls   53  ls   54  history [ejr@hobbes clean]$ !40 cd [ejr@hobbes ejr]$ 

To view session history in the bash shell:


Use the shell for a little while, changing directories, redirecting output, or doing other tasks.

Take your time. We'll wait.


Press one time.

Note that the last (previous) command you used appears on the command line, as shown in Code Listing 3.9. To reissue the command, just press .


Continue to press or to scroll back or forward through your history. When you reach a command you want to use, press .

If you see a command that's close, but not exactly what you want to use, you can edit it. Just use the and keys to move across the line, insert text by typing it in, and use or to delete text. When you've fixed the command, press (you don't have to be at the end of the line to do so).



Type history at the shell prompt to see a numbered list of previous commands you've entered.


  • Commands from the current session are kept in memory to scroll through, while commands from previous sessions are kept in the ~/.bash_history file. You can edit bash_history with any editor to delete unneeded commands or simply delete the file to get rid of the whole history file, which will then be re-created with the next command you issue. (A history of commands is a great jumping-off point to write a script to do the commands automatically. Chapter 10 gives you the specifics.)

  • When you're viewing the history, you can recycle commands by typing an exclamation point (!) and the line number of the command you want to run again. You'd type !40, for example, to rerun command 40.

  • Use history followed by a number to specify the number of items to list. For example, history 10 shows the last 10 commands.

Unix(c) Visual Quickstart Guide
UNIX, Third Edition
ISBN: 0321442458
EAN: 2147483647
Year: 2006
Pages: 251

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: