In the Unix/Linux shell environment, viewing command history, editing commands, and re-executing them are essential tasks for efficient command-line usage.
Here’s how you can perform these actions:
1. Viewing Command History:
- Use the
historycommand to display a list of previously executed commands along with their line numbers. - By default, the
historycommand displays the most recent 1000 commands, but you can configure this limit.
[root@uadev ~]# history |head
1 exit
2 cd /var/
3 du -h log
4 netstat -tuln
5 iftop
6 dnf install iftop
7 ps aux
8 pgrep sshd
9 pgrep colord
10 pgrep auditd
[root@uadev ~]#
2. Re-executing Commands:
- Use the
!nsyntax to re-execute a specific command by its line number, wherenis the line number of the command in the history.- Example:
!123re-executes the command with line number 123.
- Example:
- Use
!!to re-execute the last command. - Use
!stringto re-execute the most recent command that starts withstring.- Example:
!lsre-executes the most recent command that starts withls.
- Example:
[root@uadev ~]# !8
pgrep sshd
982
1862
1889
[root@uadev ~]#
[root@uadev ~]# !!
pgrep sshd
982
1862
1889
[root@uadev ~]#
3. Editing Commands:
- Use the arrow keys (up and down) to navigate through the command history.
- Press
Ctrl + Rto search backward through the command history.- Start typing a part of the command you want to search for, and press
Ctrl + Rto search. - Press
Ctrl + Ragain to find the previous matching command.
- Start typing a part of the command you want to search for, and press
[root@uadev ~]#
(failed reverse-i-search)`date': date
- Press
Ctrl + Gto cancel the search and revert to the original command line. - Use the
fccommand to open the default text editor (usuallyviornano) to edit a range of commands in the history.- Example:
fcopens the default text editor with the last command for editing. - After editing and saving the changes, the commands are executed sequentially.
- Example:
[root@uadev ~]# fc
ls -lrt
whoami
date
[root@uadev ~]# fc
ls -lrt
total 4
-rw-------. 1 root root 879 May 27 22:49 anaconda-ks.cfg
whoami
root
date
Fri Jun 7 10:04:55 PM IST 2024
[root@uadev ~]#
Tips:
- Use
history | grep keywordto search for commands containing a specific keyword. - Use
history -cto clear the command history. - To preserve command history between sessions, configure the
HISTFILEenvironment variable in your shell configuration file (e.g.,.bashrc,.zshrc).
Efficiently viewing command history, editing commands, and re-executing them are essential skills for command-line users. These techniques can help streamline your workflow, save time, and avoid repetitive typing. By mastering these commands and shortcuts, you can become more productive and effective in using the Unix/Linux shell environment.