Unlock Bash Power: Advanced Uses of the history Command
This guide explores Bash's built‑in history command, revealing hidden features like event designators, string search, relative indexing, and quick substitution to boost shell productivity.
Many users only use history to list past commands, but Bash's built‑in history offers a rich set of capabilities far beyond simple listing.
Why Bash history is special
Bash inherits a long lineage from the original Bourne shell, making its history the most feature‑rich among Linux shells. Unlike external binaries located in /usr/bin or /usr/local/bin, history is a shell builtin and therefore does not appear in PATH or have a physical file location.
$ which history
which: no history in [PATH]You can verify it is a builtin with:
$ type history
history is a shell builtin
$ help history
history: history [-c] [-d offset] [n] ...Basic usage – viewing command history
$ echo "hello"
hello
$ echo "world"
world
$ history
1 echo "hello"
2 echo "world"
3 historyEvent designators
Use ! followed by a history number to re‑execute a command, e.g. !1 runs the first entry.
$ !1
echo "hello"
helloRelative references like !-3 fetch the third‑last command, and !! repeats the previous command.
$ echo "alvin"
alvin
$ !!
echo "alvin"
alvinString search
Prefix search: !echo runs the most recent command starting with echo. Substring search: wrap the pattern with ?, e.g. !?alvin?. If the pattern appears at the end, the trailing ? can be omitted.
$ !?alvin
echo "alvin"
alvinWhen multiple matches exist, only the most recent matching command is executed.
Quick substitution
Replace the first occurrence of a string in the previous command using ^old^new syntax.
$ echo "hello"
hello
$ ^hello^alvin
echo "alvin"
alvinOnly the first occurrence is replaced; if the target appears twice, the second remains unchanged.
Putting it all together
The examples above only scratch the surface. Bash’s history can also write to files, merge histories, and more, offering powerful ways to manage and reuse command lines without typing them again.
Experiment with the various options to discover how much you can accomplish with just the history builtin.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
