- How To Search Shell Command History
- Shell history search command
- Emacs Line-Edit Mode Command History Searching
- fc command
- Delete command history
- The Power of Linux “History Command” in Bash Shell
- 1. List Last/All Executed Commands in Linux
- 2. List All Commands with Date and Timestamp
- 3. Filter Commands in History
- 4. Ignore Duplicate Commands in History
- 5. Unset export Command
- 6. Save export Command Permanently
- 7. List Specific User’s Executed Commands
- 8. Disable Storing History of Commands
- 9. Delete or Clear History of Commands
- 10. Search Commands in History Using Grep Command
- 11. Search Lastly Executed Command
- 12. Recall Last Executed Command
- 13. Recall Lastly Executed Specific Command
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- How can I see all of the bash history?
- 5 Answers 5
- How To Use Bash History Commands and Expansions on a Linux VPS
- Introduction
- Setting History Defaults
- Reviewing your Previous Bash History
- Executing Commands from your Bash History
- Scrolling through Bash History
- Searching through Bash History
- Searching after You’ve Typed Part of the Command
- Getting Familiar with More Advanced History Expansion
- Event Designators
- Word Designators
- Modifiers
- Conclusion
How To Search Shell Command History
Q. How do I search old command history under bash shell? How do I display or modify previous commands?
A. Almost all modern shell allows you to search command history if enabled by user. Use history command to display the history list with line numbers. Lines listed with with a * have been modified by user.
Shell history search command
Type history at a shell prompt:
$ history
Output:
Sample output:
To search particular command, enter:
$ history | grep command-name
$ history | egrep -i ‘scp|ssh|ftp’
Emacs Line-Edit Mode Command History Searching
To get previous command containing string, hit [CTRL]+[r] followed by search string:
To get previous command, hit [CTRL]+[p]. You can also use up arrow key.
To get next command, hit [CTRL]+[n]. You can also use down arrow key.
fc command
fc stands for either “find command” or “fix command. For example list last 10 command, enter:
$ fc -l 10
To list commands 130 through 150, enter:
$ fc -l 130 150
To list all commands since the last command beginning with ssh, enter:
$ fc -l ssh
You can edit commands 1 through 5 using vi text editor, enter:
$ fc -e vi 1 5
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Delete command history
The -c option causes the history list to be cleared by deleting all of the entries:
$ history -c
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
The Power of Linux “History Command” in Bash Shell
We use history command frequently in our daily routine jobs to check history of command or to get info about command executed by user. In this post, we will see how we can use history command effectively to extract the command which was executed by users in Bash shell. This may be useful for audit purpose or to find out what command is executed at what date and time.
By default date and timestamp won’t be seen while executing history command. However, bash shell provides CLI tools for editing user’s command history. Let’s see some handy tips and tricks and power of history command.
history command examples
1. List Last/All Executed Commands in Linux
Executing simple history command from terminal will show you a complete list of last executed commands with line numbers.
2. List All Commands with Date and Timestamp
How to find date and timestamp against command? With ‘export’ command with variable will display history command with corresponding timestamp when the command was executed.
Meaning of HISTTIMEFORMAT variables
3. Filter Commands in History
As we can see same command is being repeated number of times in above output. How to filter simple or non destructive commands in history?. Use the following ‘export‘ command by specifying command in HISTIGNORE=’ls -l:pwd:date:’ will not saved by system and not be shown in history command.
4. Ignore Duplicate Commands in History
With the below command will help us to ignore duplicate commands entry made by user. Only single entry will be shown in history, if a user execute a same command multiple times in a Bash Prompt.
5. Unset export Command
Unset export command on the fly. Execute unset export command with variable one by one whatever commands have been exported by export command.
6. Save export Command Permanently
Make an entry as follows in .bash_profile to save export command permanently.
7. List Specific User’s Executed Commands
How to see command history executed by a specific user. Bash keeps records of history in a ‘
/.bash_history’ file. We can view or open file to see the command history.
8. Disable Storing History of Commands
Some organization do not keep history of commands because of security policy of the organization. In this case, we can edit .bash_profile file (It’s hidden file) of user’s and make an entry as below.
Save file and load changes with below command.
Note: If you don’t want system to remember the commands that you have typed, simply execute below command which will disable or stop recording history on the fly.
Tips: Search ‘HISTSIZE‘ and edit in ‘/etc/profile’ file with superuser. The change in file will effect globally.
9. Delete or Clear History of Commands
With up and down arrow, we can see previously used command which may be helpful or may irate you. Deleting or clearing all the entries from bash history list with ‘-c‘ options.
10. Search Commands in History Using Grep Command
Search command through ‘.bash_history‘ by piping your history file into ‘grep‘ as below. For example, the below command will search and find ‘pwd‘ command from the history list.
11. Search Lastly Executed Command
Search previously executed command with ‘Ctrl+r’ command. Once you’ve found the command you’re looking for, press ‘Enter‘ to execute the same else press ‘esc‘ to cancel it.
12. Recall Last Executed Command
Recall a previously used specific command. Combination of Bang and 8 (!8) command will recall number 8 command which you have executed.
13. Recall Lastly Executed Specific Command
Recall previously used command (netstat -np | grep 22) with ‘!‘ and followed by some letters of that particular command.
We have tried to highlight power of history command. However, this is not end of it. Please share your experience of history command with us through our comment box below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
How can I see all of the bash history?
First let me show an example below.
In shell(1) I did the following command.
And after that, open another shell(2) and look at history.
In this case, the shell can not see the history executed by shell(1), but I want to see all of the bash history in every shell.
So my question is how can I see all of the bash history? Does anybody know how to hack?
Thank you very much in advance!
5 Answers 5
would also work, although I tend to just use
and then use / to search
/.bash_history shows only the commands outside of the virtual environment.
/.zsh_history if you installed zsh
You should look into the histappend shell option and the -a flag to history :
If set, the history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file.
history
-a Append the «new» history lines (history lines entered since the beginning of the current bash session) to the history file.
If you put history -a into your PROMPT_COMMAND , you’ll get an always-up-to-date .bash_history file.
Edit your .bashrc and append this to it’s end:
You can install something like Advanced Shell History, which will log each command to a sqlite3 database. It comes with a tool for querying the database from the command line. https://github.com/barabo/advanced-shell-history
With this setup, you will have a unified view of command history across all sessions. You also get things like command history for the current working directory (or subtree), command exit code, command duration, etc.
Full disclosure: I wrote and maintain the tool.
As several have noted, you need to use shopt -s histappend . Check by running shopt and verifying that histappend is ‘on’.
To ensure that each command (across multiple concurrent shells) appears in the history for each of those shells, add this at the end of your .bashrc file:
-a: appends the new history lines (history lines entered since the beginning of the current Bash session) to the history file.
-c: clears the history list.
-r: reads the current history file and append its contents to the history list.
Run source .bashrc or create new sessions and in several terminal windows enter the comment #Tn in each. Then on one terminal, enter history | tail -N to see the last N lines. You should see all of the comments entered on the different terminals.
Источник
How To Use Bash History Commands and Expansions on a Linux VPS
Published on March 5, 2014
Introduction
While working in a server environment, you’ll spend a lot of your time on the command line. Most likely, you’ll be using the bash shell, which is the default of most distributions.
During a terminal session, you’ll likely be repeating common commands often, and typing variations on those commands even more frequently. While typing each command again can be good practice in the beginning, at some point, it crosses the line into being disruptive and an annoyance.
Luckily, the bash shell has some fairly well-developed history functions. Learning how to affectively use and manipulate your bash history will allow you to spend less time typing and more time getting actual work done. Many developers are familiar with the DRY philosophy of Don’t Repeat Yourself. Effective use of bash’s history allows you to operate closer to this principle and will speed up your work flow.
In this guide, we will be checking out these features on an Ubuntu 12.04 VPS instance, but almost all modern Linux distributions should operate in a similar way. Let’s get started!
Setting History Defaults
Before we begin actually using the history, let’s adjust some bash settings to make it more useful.
Bash allows you to adjust the number of previous commands that it stores in history. It actually has two separate options for this: the HISTFILESIZE parameter configures how many commands are kept in the history file, while the HISTSIZE controls the number stored in memory for the current session.
This means you can set a reasonable cap for the size of history in memory for the current session, and have an even larger history saved to disk that you can examine at a later time. By default, bash sets very conservative values for these options, so we’ll expand them to take advantage of a larger history. Some distributions already increase the default bash history settings with slightly more generous values.
/.bashrc file with an editor to change these settings:
Search for both the HISTSIZE and HISTFILESIZE parameters. If they are set, feel free to modify the values. If these parameters aren’t in your file, add them now. For our purposes, we can easily get away with saving 10000 lines to disk and loading the last 5000 lines into memory. This is a conservative estimate for most systems, but adjust it down if you see a performance impact:
By default, bash writes its history at the end of each session, overwriting the existing file with an updated version. This means that if you are logged in with multiple bash sessions, only the last one to exit will have its history saved.
We can work around this by setting the histappend setting, which will append instead of overwrite the history. This may be set already, but if it is not, you can enable this by adding this line:
If we want to have bash immediately add commands to our history instead of waiting for the end of each session (to enable commands in one terminal to be instantly be available in another), we can also set or append the history -a command to the PROMPT_COMMAND parameter, which contains commands that are executed before each new command prompt.
To do this correctly, we need to do a bit of a hack. We need to append to the history file immediately with history -a , clear the current history in our session with history -c , and then read the history file that we’ve appended to, back into our session history with history -r .
You can do this like so:
When you are finished, save the file and exit.
To implement your changes, either log out and back in again, or source the file by typing:
Reviewing your Previous Bash History
The way that we review bash history is to use the history command. This will print out our recent commands, one command per line. This should output, at most, the number of lines you selected for the HISTSIZE variable. It will probably be fewer at this point:
It also prints the history number for each command. Each command is associated with a number for easy reference. You will see why this is useful in a moment.
We can truncate the output by specifying a number after the command. For instance, if we want to only see the last 5 commands typed, we can type:
To find all of the history commands that involve a certain string, an easy way of getting an overview is to simply pipe it to grep. For example, we can search for the lines that have cd by typing:
Executing Commands from your Bash History
Printing off our history is nice, but, by itself, it doesn’t really help us access those commands easily, except as a reference. However, we can quickly recall any of the returned output using a special syntax.
We can recall any of our previous history by its number preceded by an exclamation point (!). For instance, if your history looks like mine above, you could see the man page for the history command quickly by typing:
This will immediately recall and execute the command associated with the history number 51.
We can also execute commands relative to our current position. We can do this by using the !-n syntax, where “n” is replaced by the number of commands ago we want to recall.
For instance, if we want to recall and execute a command that we typed before our most recent one, we could type !-2 . So if we listed the contents of a long directory path, echoed something and wanted to list again, our session might look like this:
To re-execute the previous command, bash provides a shortcut that we can use instead of !-1 . The shortcut is !! , which will substitute the most recent command and execute:
Many people use this when they type a command that they realize they needed sudo privileges to execute. Typing sudo !! will re-execute the command with sudo in front of it. The session might look like this:
This demonstrates another property of this syntax. They are pure substitutions, and can be incorporated within other commands at will.
Scrolling through Bash History
There are a few ways that we can scroll through our bash history, putting each successive command on the command line to edit.
The most common way of doing this is to press the up arrow key at the command prompt.
Each additional press of the up arrow key will take you further back in your command line history. If you need to go the other direction, the down arrow key traverses the history in the opposite direction, finally bringing you back to your current prompt.
If moving your hand all the way over to the arrow keys seems like a big hassle, you can move backwards in your command history using the CTRL-p combination, and use the CTRL-n combination to move forward in history again.
If you want to jump back to the current command prompt, you can do so by typing Meta-> . In most cases, the “meta” key and the “>” will mean typing ALT-Shift-. . This is useful if you find yourself far back in your history and want to get back to your current command.
You can go to the first line of your command history by doing the opposite maneuver and typing Meta- . This typically means pressing ALT-Shift-, .
To summarize, these are some keys to scroll through the history and jump to either end:
UP arrow key: Scroll backwards in history
CTRL-p: Scroll backwards in history
DOWN arrow key: Scroll forwards in history
CTRL-n: Scroll forwards in history
ALT-Shift-.: Jump to the end of the history (most recent)
ALT-Shift-,: Jump to the beginning of the history (most distant)
Searching through Bash History
Although piping the history command through grep is definitely the easiest way of accomplishing some procedures, it isn’t ideal in many situations.
Bash includes search functionality for its history. The typical way of utilizing this is through searching backwards in history (most recent results returned first) using the CTRL-r key combination.
For instance, you can type CTRL-r , and begin typing part of the previous command. You only have to type out part of the command. If it matches an unwanted command instead, you can press CTRL-r again to see the next result.
If you accidentally pass the command you wanted, you can move in the opposite direction by typing CTRL-s . This also can be useful if you’ve moved to a different point in your history using the keys in the last section and wish to search forward.
Note: In many terminals, the CTRL-s is actually mapped to suspend the terminal session. This will intercept any attempts to pass CTRL-s to bash, and will “freeze” your terminal. To unfreeze, simply type CTRL-q to unsuspend the session.
This suspend and resume feature is not needed in most modern terminals, and we can turn it off without any problem by typing:
We should add this to our
/.bashrc file to make this change permanent as well.
If you try again, it should work as expected to allow you to search forwards.
Searching after You’ve Typed Part of the Command
A common scenario to find yourself in is to type in part of your command, and then realize that you have executed it previously and can search the history for it.
The correct way of searching using what is already on your command line is to move your cursor to the beginning of the line with CTRL-a , call the reverse history with CTRL-r , paste the current line into the search with CTRL-y , and then using the CTRL-r again to search in reverse.
For instance, suppose we want to update our package cache on an Ubuntu system. We’ve already typed this out recently, but we didn’t think about that until after we’ve typed the sudo in again:
At this point, we realize that this is an operation we’ve definitely done in the past day or so. We can hit:
This moves our cursor to the beginning of the line.
We call our reverse incremental history search. This has a side effect of copying all of the content on the command line that was after our cursor position. It puts this into a clipboard.
We paste the command segments that we’d just copied from the command line into the search.
We move backwards in our history, searching for commands containing the content we’ve just pasted.
This might seem like a huge pain in the neck, but it’s actually not too bad when you get used to it. It is extremely helpful when you find yourself in that awkward position where you’ve typed out half of a complex command and know you’re going to need the history to finish the rest.
To make it easier, you can think of this as a simpler, compound command:
Getting Familiar with More Advanced History Expansion
We’ve already touched on some of the most basic history expansion techniques that bash provides. Some of the ones we’ve covered so far are:
- !!: Expand to the last command
- !n: Expand to command with history number “n”.
- !-n: Expand to command that was “n” number of commands before the current command in history.
Event Designators
The above three examples are instances of event designators. These generally are ways of recalling previous history commands using certain criteria. They are the selection portion of our available operations.
We can execute the last “ssh” command by typing something like:
This searches for lines beginning with “ssh”. If we want to search for a string that doesn’t happen at the beginning of the command, we can surround it with “?” characters. For instance, to repeat our least apt-cache search command, we could probably get away with typing:
Another trick that you can try is a variation on the !! last history command. You can do a quick search and replace by typing:
This will recall the previous command (just like “!!”), search for an instance of “original” within the command string, and replace it with “replacement”. It will then execute the command.
This is useful for dealing with things like misspellings. For instance:
Word Designators
After event designators, we can add a colon (:) and add on a word desginator to select a portion of the matched command.
It does this by dividing the command into “words”, which are defined as any chunk separated by whitespace. This allows us some interesting opportunities to interact with our command parameters.
The word numbering starts at the initial command as “0”, the first argument as “1”, and continues on from there.
For instance, we could list the contents of a directory, and then decide we want to change to it, like this:
In cases where we are operating on the last command, we can actually compress this by removing the second “!»and the colon, like this:
This will operate in the same way.
We can refer to the first argument as ”^“ and the final argument as ”$“ if that makes sense for our purposes. These are more helpful when we use ranges instead of specific numbers. For instance, we have three ways we can get all of the arguments from a previous command into a new command:
The lone ”“ expands to all portions of the command being recalled other than the initial command. Similarly, we can use a number followed by ”“ to mean that everything after the specified word should be included.
Modifiers
The last thing that we can do to augment the behavior of the history line we are recalling is to modify the behavior of the recall to manipulate the text itself. Modifiers are added after an additional colon (:) character at the end of the expansion.
For instance, we can chop off the path leading up to a file by using the «h” modifier (it stands for “head”), which removes the path up until the final slash (/) character. Be aware that this won’t work the way you want it to if you are using this to truncate a directory path and the path ends with a trailing slash.
A common use-case for this is if we are modifying a file and realize we’d like to change to the file’s directory to do operations on related files.
For instance, we could read the copyright information of a package:
After being satisfied that we can use the package for our needs, we may want to change to the directory. We can do this by calling the cd command on the argument chain and chopping off the filename at the end:
After we’re there, we may want to open that copyright file again to double check, this time in a pager.
We can do the reverse manipulation, chopping off the path and using only the filename with the “t” modifier for “tail”. We can search for our last cat operation, and use the “t” flag to pass only the file name:
You could just as easily keep the full absolute path name and this command would work correctly in this instance. However, there are other times where this isn’t true. We could be looking at a file nested within a few sub directories below our current directory using a relative path, change to the subdirectory using the “h” modifier, and then we wouldn’t be able to rely on the relative path name to reach the file any more.
Another extremely helpful modifier is the “r” modifier, which strips the trailing extension. This could be useful if you are using tar to decompress a file and want to change into the directory afterwards. Assuming the directory produced is the same name as the file, you could do something like:
If your tarball uses the tar.gz extension instead of tgz , you can just pass the modifier twice:
A similar modifier, “e”, removes everything besides the trailing extension.
If you do not want to execute the command that you are recalling, and simply want to find it, you can use the “p” modifier to have bash echo the command instead of executing it.
This is useful if you are unsure of if you’re selecting the correct piece. This not only prints it, but also puts it into your history for further editing if you’re unhappy with it.
For instance, imagine you ran a find command on your home directory and then realize that you want to run it from the root (/) directory. You could check that you’re making the correct substitutions like this (assuming the original command is #119):
If the outputted command we cobbled together is correct, we can execute it easily with:
This would probably be easier if we could just make substitutions in our command easily. We can do that using the s/original/new/ syntax.
For instance, we could have accomplished that by typing:
This will substitute the first instance of the search pattern. We can substitute every match by also passing the “g” flag with the “s”. For instance if we want to create files named file1, file2, and file3, and then want to create directories called dir1, dir2, dir3, we could do this:
Conclusion
You should now have a good idea of how you can leverage the history operations available to you. Some of these will probably be more useful than others, but it is good to know that bash has these capabilities in case you find yourself in a position where it would be helpful to dig them up.
If nothing else, the history command alone, the reverse search, and the simple history expansions should help you speed up your work flow.
Источник