Bash histverify: Edit History Commands Before They Run
Linux’s history command helps you quickly find and reexecute commands you’ve run before.
Running a command from history is as simple as typing !<the_command_id> and hitting Enter. You can find the command ID to the left of each command.
For example, !1998 runs the command number 1998 in the history file.
⚠️ !<the_command_id> executes the given command immediately. Rerunning some commands (e.g., rm, git reset) this way can lead to unintended consequences.
💡 The ! operator is known as the history expansion operator.
Accessing the history is helping me a lot. For example, I often do WordPress plugin updates and find myself repeating standard commits like this:
git commit -m "Update Yoast SEO plugin: 26.8 → 27.1.1"
The downside is that I need to copy and paste it every time to modify the plugin name and version information. But what if I can edit the command before running it?
In Bash, there’s an option called histverify that can be handy in this case. Here’s what the Bash Reference Manual says about histverify:
If the histverify shell option is enabled, and Readline is being used, history substitutions are not immediately passed to the shell parser. Instead, the expanded line is reloaded into the Readline editing buffer for further modification.
Put simply, histverify:
- stands as a safeguard between the user and immediate command execution
- prints the command on the cursor line, allowing us to edit it
Note: histverify may be disabled by default. That was the case in my distro.
To check whether histverify is enabled in your shell, simply run:
shopt histverify
Here’s how to turn it on:
shopt -s histverify
Here, -s stands for set or enable.
To turn histverify back off (not recommended), use the -u flag instead:
shopt -u histverify
-u stands for unset or disable.
Note: shopt and histverify are Bash-specific features. If you use a shell other than Bash, look for options available in it.
Keep in mind that shopt enables histverify only for the current shell session. The setting will be lost the next time you start a new shell. If you want to enable histverify permanently, then follow these steps:
- Add
shopt -s histverifyinstruction to the end of your~/.bashrcconfiguration file - Save the file
- Run
source ~/.bashrcto apply the changes
Stay safe. And let the good people explore good content. 🙂