Adsense Leaderboard Ad

11.19.2017

How Repeat Your Last Command in BASH

Question sent in by Olivia from New Jersey

Q: I am using an old Dell laptop that my Dad gave me and the arrow keys do not work.  Is there a way to execute the last command I ran since I can't use the up arrow.  Also is there a way to scroll through my history without the up arrow?

A: Yes, as with anything Linux there are multiple ways of doing it.  Let's explore a couple and talk about their downsides.

First and most simple is using the double bang (exclamation point). 

!!

The one major flaw with this is it will execute the command without letting you read it, which is different from the way scrolling up with the arrow would work. 

To get the same effect as using the up arrow once, which is showing the last command run without executing it, you can use CTRL+P.

Another option you have is using the history a little better.  You can run the following to run your last command:

!-1

Or change the number, and run any of your last commands.  For example changing the 1 to a 2 will run the second from last command.

[savona@bighat ~]$ cat /etc/redhat-release
Fedora release 25 (Twenty Five)
[savona@bighat ~]$ echo "ANOTHER COMMAND"
ANOTHER COMMAND
[savona@bighat ~]$ !-2
cat /etc/redhat-release
Fedora release 25 (Twenty Five)
[savona@bighat ~]$

Another option you have is to list out the history, then running the number of the command you want, like so:

[savona@bighat ~]$ history
    1  cat /etc/redhat-release 
    2  echo "ANOTHER COMMAND"
    3  echo "Putorius is Curious"
    4  uname -r
    5  date
    6  history
[savona@bighat ~]$ !4
uname -r
4.13.10-100.fc25.x86_64
[savona@bighat ~]$ 

For more basic information about using bash history, check out our "Basics of Using Bash History" post.

No comments:

Post a Comment