Written by Chris Gregg, with modifications by Nick Troccoli
Click here for a walkthrough video.
Your shell keeps track of the unix commands (like ls
, cd
, etc.) you execute in a history file. There are several ways to take advantage of this to quickly re-execute unix commands you have previously typed.
Viewing Your Command History
You can see your command history by typing history
:
$ history
... (potentially lots of commands)
5001 cd cs107/assignments/assign0
5002 ls
5003 cat hello.c
5004 ls
5005 cd
5006 ls
5007 ls -alrt
5008 history
$
Re-Executing Commands
If you want to execute a command again, there are several ways to do this without re-typing the entire command.
First, if you press the up arrow key, the terminal will auto-fill your most-recently-typed command. You can continue pressing the up arrow key to go through commands you executed in order of decreasing recency. You can use the down arrow key to go through commands in order of increasing recency. If you want to execute that command, just press ENTER.
Example:
$ cd cs107/assignments/assign0
$ ls
hello hello.c hello.c~ innerFolder readme.txt samples
$ cat hello.c
#include<stdio.h>
#include<stdlib.h>
int main() {
printf("Hello, World!\n");
return 0;
}
(type up arrow twice)
$ ls
hello hello.c hello.c~ innerFolder readme.txt samples
$
Second, if you type an exclamation point (also known as bang) followed by a character or a string and then enter, you will run the last command that starts with that character or string. E.g.,
$ ls -a
. .. hello hello.c hello.c~ innerFolder readme.txt samples
$ cd ..
$ !l
ls -a
. assign0 assign2 .do_not_look.txt file2.txt
.. assign1 assign3 file1.txt .this_is_hidden.txt
$
Typing !l
runs ls -a
again, because the previous command that started with l
was ls -a
.
Finally, if you press Ctl-r
, you can then start typing characters and the line will start being populated with the last command that starts with the characters you have typed. This is easier to see in the video linked at the top of the page; also try it yourself!