Linux history Command

Linux history Command

Linux history command is a powerful tool that allows you to review and manage your past commands. It provides a record of the commands you have executed in your terminal, making it easy to repeat or modify them.

As a Linux user, you can use history to search for specific commands, filter the output, and even save or load your command history to a file.

Linux history Command Syntax:

history [options]

Prerequisites to Use Linux history Command

To learn How to use history command in Linux, provide the options below:

  • A Linux VPS running a compatible Linux distribution (e.g., Ubuntu, Debian, CentOS).
  • A non-root user with sudo privileges.
  • Access to Terminal.

13 Practical Examples of history Command in Linux

Let’s go through history Luinux tutorial and review the most used examples of Linux history command.

1. Basic Usage of the history Command

Running the history command without options will display a list of recently executed commands in the current terminal session.

This output typically includes the command number, the time it was executed, and the actual command itself.

Syntax:

history

Output:

  1  2024-08-24 00:01:23 ls
  2  2024-08-24 00:01:25 cd Documents
  3  2024-08-24 00:01:26 cat myfile.txt
  4  2024-08-24 00:01:30 sudo apt update

2. Limiting the Number of history Entries

The Linux history command is used to attach the specified number of entries from the command history list to the history command.

Syntax:

history -n <number>

When you use the -n option with the history command, it displays only the specified number of recent commands.

Example:

history -n 10

Output:

The -n 10 display the last 10 commands executed.

3. Finding Specific Commands in Your history

The history command in Linux allows you to view, search, and manipulate your past commands.

Syntax:

history | grep <keyword>

The history command, when piped to grep, will filter the history list to display only the commands that contain the specified keyword or pattern.

Example:

history | grep sudo

Output:

It will find all commands that contain the word “sudo” in the history.

4. Protecting Sensitive Information in Command history

When you enter sensitive information (like passwords) on the command line, it can be saved to your command history.

This poses a security risk, as anyone with access to your history file can potentially view this information.

  • Preventing Sensitive Information from Being Saved:

Immediate Deletion: Use the following command structure to delete the last command (containing the sensitive information) immediately after entering it:

special-app my-secret-password; history -d $(history 1)

Replace special-app with the actual application name and my-secret-password with your sensitive information.

Ignoring Lines Starting with a Space: A simpler method is to prepend a space to the command containing sensitive information:

special-app another-password

This prevents the command from being added to the history.

  • Explanation:

The semicolon (;) separates two commands. The first command (special-app my-secret-password) executes the application with the sensitive information.

The second command (history -d $(history 1)) immediately deletes the last command from the history.

The $(history 1) part uses command substitution to get the number of the last command and pass it to the -d option of history.

  • Additional Considerations:

Regularly Clear Your History: To minimize the risk of sensitive information being exposed, regularly clear your command history using history -c.

Use a Password Manager: Consider using a password manager to store and manage your passwords securely.

5. Customizing history Behavior with .bashrc File

The .bashrc file is a hidden configuration file located in your home directory. It is executed automatically whenever you open a new terminal session.

This file can be used to customize your shell environment, including the behavior of the history command.

Syntax:

To edit the .bashrc file, you can use a text editor like gedit, nano or vim.

Example:

To add a line to the .bashrc file that sets the maximum number of commands stored in the history to 1000, you would add the following line:

export HISTSIZE=1000

The HISTSIZE environment variable controls the maximum number of commands stored in the history.

Output:

After saving the changes to your .bashrc file and opening a new terminal session, the history command will now only store the last 1000 commands.

Note:

The HISTTIMEFORMAT environment variable allows you to customize the format of timestamps displayed in the history command. You can use various arguments to specify the desired format.

Date and Time Components:

  • %a: Abbreviated weekday name (e.g., Sun, Mon, Tue)
  • %A: Full weekday name (e.g., Sunday, Monday, Tuesday)
  • %b: Abbreviated month name (e.g., Jan, Feb, Mar)
  • %B: Full month name (e.g., January, February, March)
  • %d: Day of the month (01-31)
  • %H: Hour (00-23, 24-hour format)
  • %I: Hour (01-12, 12-hour format)
  • %m: Month (01-12)
  • %M: Minute (00-59)
  • %p: AM or PM
  • %S: Second (00-59)
  • %y: Year (00-99)
  • %Y: Year (four digits)

Example:

To display timestamps in the format “YYYY-MM-DD HH:MM:SS”, set HISTTIMEFORMAT as follows:

export HISTTIMEFORMAT="%Y-%m-%d %T"

Now, when you run the history command, the timestamps will be displayed in this format.

6. Repeating Commands in history

You can use Linux history command to review and repeat previously executed commands.

By using the below techniques, you can quickly and efficiently rerun commands without having to retype them.

This can be especially helpful when working on repetitive tasks or when you need to correct errors in previous commands.

Examples:

  • To repeat a specific command, run the command below to run the third command, you would use:
!3
  • To refer to commands from the end of the list, run the command below. Here, it will repeat the seventh last command:
!-7
  • To repeat the last command, use double exclamation points (!!). This is a shortcut for repeating the most recently executed command.
!!
  • Also, to repeat a command, type the correct number from the list or use double exclamation points to repeat the last command you executed:

To repeat a previous command, use the number (again, without spaces), one exclamation point, and a hyphen (-).

For example, use the command below to repeat the 15th previous command, you would type the following:

!-15

7. Searching for Commands by String in history

To quickly repeat the last command that begins with a specific string, you can use the following syntax:

!<string>

Replace <string> with the desired string. For example, to repeat the last command that starts with “sudo”, you would type:

!sudo

To avoid accidentally executing the wrong command, it’s recommended to use the :p modifier.

This modifier instructs history to print the matching command to the terminal without executing it. You can then review the command and decide if it’s the one you want to run.

!<string>:p

To find and execute the first matching command that contains a specific string, use the following syntax:

!?<string>

Replace <string> with the desired string. For example, to find and execute the first command containing “aliases”, you would type:

!?aliases

This will search through your command history and execute the first command that matches the specified string.

8. Modifying the Last Command

The caret (^) symbol is a powerful tool in the Linux shell for modifying the last command before executing it. This is especially useful for correcting typos, adding or removing command-line options, or changing parameters.

To use Caret:

  1. Type a caret (^) followed by the text you want to replace.
  2. Type another caret (^) followed by the replacement text.
  3. Press Enter.

Example:

If you accidentally typed “shhd” instead of “sshd” in the following command:

sudo systemctl start shhd

Then, correct it using the caret:

^shhd^sshd^

This will modify the last command to:

sudo systemctl start sshd

Consider below Notes:

  • You can use multiple caret pairs to make multiple replacements within the same command.
  • If you need to replace a string that contains a caret, you can escape it using a backslash (\).
  • The caret modification works best for simple changes. For more complex modifications, it might be easier to retype the entire command.

9. Deleting Commands from history

Linux history command provides a way to remove unwanted entries from your command history. This can be useful for clearing sensitive information or simply keeping your history organized.

  • Using the -d Option:

To delete a specific command from the history, you can use the -d option followed by the command number.

For example, to delete the command at position 59, you would type:

history -d 59

Using grep to Find and Delete:

You can combine grep command and history -d to find and delete commands based on their content.

For instance, to find and delete all commands containing “shhd”, you could use:

history | grep shhd
history -d <number of the matching command>
  • Deleting a Range of Commands:

To delete a range of commands, specify the starting and ending positions using the -d option. For example, to delete commands 44 through 54:

history -d 44 54
  • Deleting the Last Few Commands:

To delete the last few commands, use a negative number with the -d option. For instance, to delete the last 18 commands:

history -d -5

10. Updating the history File

The history command in Linux allows you to interact with the history file, which stores a record of your past commands.

  • Reading the History File:

When you log in or open a new terminal session, the history command automatically reads the history file, typically located at .bash_history in Bash.

  • Writing Changes to the History File:

Closing the Terminal: Changes made during a terminal session are usually written to the history file when you close the terminal or log out.

1. Using the -a Option: To write the current history to the file immediately, use:

history -a

2. Using the -w Option: To write all changes (including deletions) to the history file:

history -w

11. Clearing the history List

The history command in Linux provides a way to remove all entries from your command history.

  • Clearing the Current History:

To clear the current history within your terminal session, use:

history -c
  • Writing Changes to the History File:

To ensure that the cleared history is also saved to the history file, use:

history -w

This will permanently remove the cleared entries from the history file.

12. Repeating the history command at position

The -p option allows you to execute a command from your history by specifying its position. The position is determined by the order in which the commands were executed.

Syntax:

history -p <number>

-p <number>: Repeats the command at position <number>.

Example:

history -p 5

This command repeats the command at position 5 in your history.

Output:

The specified command will be executed, and its output will be displayed in the terminal.

13. Preventing Commands from Being Recorded in history

To temporarily disable the recording of commands in your Linux shell’s history, use the following command:

set +o history

This will prevent any subsequent commands from being added to the history list.

To re-enable command recording, use the following command:

set -o history

Note: These commands do not produce any visible output. To verify if recording is enabled or disabled, you can check the current setting using:

echo $HISTSIZE

If the output is 0, history recording is disabled. If it’s a non-zero value, it’s enabled.

Linux history Command Options

OptionDescription
-cClears the command history.
-d Deletes the command at position .
-n Displays the last of commands.
-p Repeats the command at position .
-s Adds a command to the history without executing it.
-w Saves the history to a specified file.
-f Loads the history from a specified file.
-rReverses the order of the history (newest first).
-t Displays commands executed after a specific time.
-eEdits the last command.
-lDisplays the command history in a long format, including timestamps and command numbers.
-hDisplays a brief usage message.

How to clear command history in Linux?

Use history -c to clear the current history, or history -c -w to clear both the current history and the history file.

How to search for a specific command in my history?

Use history | grep <keyword> to filter the history based on a keyword or pattern.

How to save command history to a file?

Use history -w <filename> to save the history to a specified file.

How to load a previously saved history file?

Use history -f <filename> to load the history from a specified file.

How to delete a specific command from history?

Use history -d <number> to delete the command at the given position.

Why command history is not being saved?

To troubleshoot history command, ensure that your shell configuration (e.g., .bashrc) is set up correctly to save the history.

Check if the HISTSIZE variable is set to a non-zero value.

Why the history command is not working?

to solve this issue verify that your shell is configured to use the history built-in command. Check if the HISTSIZE variable is set. If the issue persists, try restarting your terminal session.

Why I cannot edit or modify a command in my history?

The ability to edit commands in history may depend on your shell and configuration.

Some shells (like Bash) allow editing using the caret (^) symbol, but this feature may not be universally available.

Conclusion

This guide covers examples of Linux history command options to let you know how to use history command in Linux.

Now, you can start using the history command, which is invaluable for improving efficiency and productivity in your Linux workflow.

Leave a Reply

Your email address will not be published. Required fields are marked.