Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Use Bash History Commands and Expansions on a Linux VPS

A practical guide to Bash history on Linux VPS servers: list and delete entries, rerun or edit commands, control persistence and timestamps, synchronize SSH sessions, and avoid leaking credentials.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

On a Linux VPS, Bash history lets you inspect commands from the current shell, recall or edit earlier commands, and retain a useful record between SSH connections. The core tools are the history and fc builtins, history expansion with !, and the HIST* settings that control storage. Use automatic expansions for speed, fc when you need review before execution, and never enter secrets directly into a command just because history filtering is enabled.

How Bash history works on a VPS

Bash keeps an in-memory history list for an interactive shell when the -o history option is enabled. The documented default is 500 entries in memory. A shell can also load and save a disk file, normally ~/.bash_history, through the HISTFILE variable.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When Bash starts, it reads the file named by HISTFILE. When the shell exits, it writes the last HISTSIZE entries and truncates the file to HISTFILESIZE entries. If HISTFILE is unset, empty, or not writable, that shell does not save history. This distinction matters over SSH: the list you see in one connection is primarily that shell’s memory, while another connection may have a different list until you explicitly synchronize the file.

List, limit, and manage the current history list

The history builtin prints numbered entries. The number is an event number that can be used by history expansion or fc.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
Command Effect When to use it
history Displays the available numbered entries. Inspect the current shell’s recent commands.
history 20 Displays only the last 20 entries. Reduce noise when locating a command near the end of the list.
history -c Clears the in-memory list. Remove entries from the current shell before deciding whether to rewrite the file.
history -d 123 Deletes event 123 from memory. Remove one selected event.
history -d 120-125 Deletes the inclusive range 120 through 125. Remove a contiguous group of events.
history -a Appends this shell’s new entries to HISTFILE. Make commands available to other shells without waiting for logout.
history -n Reads entries not already loaded from HISTFILE. Import commands appended by another shell.
history -r Reads a history file. Load a chosen file into the current list.
history -w Writes the current list to a history file. Explicitly save the list, including after deliberate cleanup.

history -c changes memory; it does not by itself guarantee that an existing disk file has been erased. If you need the saved file to reflect a cleaned list, clear the list and then write it deliberately, checking the result and file permissions afterward.

Rerun commands with history expansion

Interactive Bash enables history expansion by default. The exclamation mark (!) is the default history expansion character. Bash reads a complete line, performs history expansion, and only then splits the result into words. Treat an expansion as a text substitution: inspect what it will become before it runs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Repeat the previous command with !!

!!

!! substitutes the immediately preceding history event. A common administrative example is retrying a command with a privilege change:

systemctl restart nginx
sudo !!

Before pressing Enter on the second line, confirm that the first command is exactly the one you intend to repeat. The expansion does not understand whether a command is safe or whether its side effects are still appropriate.

Select a numbered event with !n

history 30
!42

!42 expands to event 42 if that event exists in the current history list. Event numbers can change as the list grows, so use the immediately preceding history output rather than relying on an old number.

Recall the latest command with a prefix

!ssh

This selects the most recent event beginning with ssh. A broad prefix can match an unexpected command; display the relevant history first when the operation is destructive or affects production services.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reuse arguments with word designators

tar -czf backup-2026-10-15.tgz /srv/app
sha256sum !$

!$ means the last argument of the previous event, so the second line expands to a checksum command for the archive path. !* expands to all arguments of the previous event:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
mkdir -p /srv/app/logs
ls -ld !*

Word designators are useful when a long path or option set is correct but typing it again would invite a mistake. They can also propagate an unintended argument, so verify the expanded line.

Make a quick substitution

grep -n 'Listen 80' /etc/nginx/nginx.conf
^80^443^

The caret form substitutes the first matching text in the previous command and executes the result. Here it changes the first 80 to 443. For more controlled edits, use fc instead of relying on a compact substitution.

Edit and rerun safely with fc

The fc builtin can list, edit, and re-execute a selected range of history. The GNU Bash Reference Manual describes it as a command that lists or edits and re-executes part of the history list.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

List a range

fc -l

fc -l lists a recent range. You can provide event numbers, negative offsets, or a command-name prefix. Listing first is useful when several similar maintenance commands appear together.

Open commands in an editor

fc -e "$EDITOR" 120 125

This opens events 120 through 125 in a temporary file using the editor named by EDITOR. When you leave the editor, Bash executes the resulting text. Review every line before saving: removing a line, changing an option, or inserting a command changes what will run. If EDITOR is not set, Bash uses its configured default editor behavior; set it explicitly when working on a server with several accounts or profiles.

Substitute text in one event

fc -s old=new 120

This substitutes the specified text and reruns event 120. It is convenient for a predictable correction, but it is still an execution command, not a preview. Use fc -l first and choose an editor when the replacement could match more than one location.

Understand quoting and literal exclamation marks

History expansion occurs before normal word splitting. A backslash can suppress special handling of the next character, and single quotes inhibit history expansion. Characters inside double quotes may still be expanded; inside double quotes, escape an exclamation mark with a backslash.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
echo 'Release!'

The single-quoted form prints a literal exclamation mark. In double quotes, use:

echo "Release!"

These rules explain surprising errors when a password-like string, YAML value, or application argument contains !. Expansion is enabled in interactive shells by default, while a non-interactive shell normally starts with it off.

Disable expansion for a shell

set +H

set +H disables history expansion in the current shell. Use it in scripts and in interactive work where literal exclamation marks are expected. To enable it again, run:

set -H

Changing this setting affects only the shell in which you run it unless you place the command in a startup configuration. A practical VPS policy is to leave expansion disabled in scripts and enable it interactively only when the speed benefit outweighs the review risk.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Control retention with HISTSIZE and HISTFILESIZE

Variable Controls Example
HISTSIZE Number of commands retained in the in-memory list and the number Bash writes on exit. HISTSIZE=2000
HISTFILESIZE Maximum number of lines or entries retained in the history file after truncation. HISTFILESIZE=5000
HISTFILE Path to the file used for loading and saving history. HISTFILE=$HOME/.bash_history
HISTTIMEFORMAT strftime format used when Bash displays timestamps. HISTTIMEFORMAT='%F %T '

Set values for the current shell with export when child Bash processes should inherit them:

export HISTSIZE=2000
export HISTFILESIZE=5000
export HISTFILE="$HOME/.bash_history"

The documented default for HISTSIZE is 500 entries. Choose larger values only when the resulting retention is acceptable for the account and server; a larger file preserves more operational context but also preserves more potentially sensitive command text.

Add timestamps that survive SSH sessions

To display timestamps with history, set an strftime format:

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
export HISTTIMEFORMAT='%F %T '

The %F and %T fields display an ISO-style date and a 24-hour time. When HISTTIMEFORMAT is set, Bash writes timestamp markers to the history file. Those markers preserve timing across sessions and delimit multiline entries.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Timestamp display is not a security audit trail. It records what Bash saves for that account; commands run by another shell, another user, a different shell program, or a process that never enters Bash history may not appear.

Keep history coherent across simultaneous SSH connections

Multiple SSH windows for the same account can otherwise overwrite or hide each other’s entries. Enable the histappend shell option so Bash appends on exit rather than replacing the file:

shopt -s histappend

For an explicit synchronization cycle, append this shell’s new lines, then import lines written by other shells:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
history -a
history -n

Run history -a after a meaningful command or at a deliberate checkpoint. Run history -n before searching for work performed in another SSH window. This is cooperative synchronization, not a locking or tamper-proof audit mechanism; two shells can still be editing the same file, and file permissions determine who can read or alter it.

A practical interactive setup

export HISTFILE="$HOME/.bash_history"
export HISTSIZE=2000
export HISTFILESIZE=5000
export HISTTIMEFORMAT='%F %T '
shopt -s histappend

Place settings you want for every interactive Bash session in the account’s appropriate Bash startup file, then open a new SSH connection to verify them. Keep environment-specific choices separate: a shared administrative account, a personal account, and a restricted service account should not automatically have identical retention policies.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Filter routine noise, but do not treat filters as secret storage

HISTCONTROL provides several built-in policies:

  • ignorespace skips a line whose first character is a space.
  • ignoredups skips a line identical to the immediately preceding history entry.
  • ignoreboth combines ignorespace and ignoredups.
  • erasedups removes earlier matching entries before saving the current one.

For example:

export HISTCONTROL=ignoreboth:erasedups

HISTIGNORE adds pattern-based filtering. A simple pattern can omit routine commands:

export HISTIGNORE='ls:pwd:history'

Patterns are Bash history filters, not a complete secret-management system. Do not type passwords, API tokens, private keys, or other credentials directly into a command merely because it begins with a space or matches HISTIGNORE. A secret can still appear in process listings, terminal recordings, shell tracing, centralized audit logs, copied transcripts, application logs, or another user’s monitoring system. Use an interactive prompt, a protected file, an agent, or the service’s supported secret mechanism instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If a secret has already entered history, remove the event from the in-memory list with history -d (or clear the list), then deliberately rewrite the history file. Also rotate the exposed credential: deleting a line does not undo copies that may already exist elsewhere.

Choose the right method for the job

Method Speed Reviewability Persistence behavior Exposure considerations
!!, !n, !$, !* Fastest; a short substitution. Low unless you inspect the expanded line. Uses the current shell’s list. Can silently reuse an unsafe argument.
history plus a command Moderate; explicit event discovery. Good for confirming the number and text. Shows memory until you read or append the file. Displays command text to anyone who can view the terminal.
fc -e Slower than expansion. Highest; you edit and inspect before execution. Executes selected history after the editor exits. Temporary editor buffers and screen sharing still matter.
history -a and history -n Explicit synchronization. Clear about what is being exchanged. Coordinates multiple shells through HISTFILE. Depends on file permissions and concurrent writers.

Use expansion for a harmless, obvious repetition; use numbered selection when you have verified the event; and use fc when a command needs alteration or a production change deserves a visible review step.

VPS troubleshooting checklist

history is empty or missing old commands

  • Check whether history is enabled: set -o | grep history.
  • Check the active file and limits: printf '%sn' "$HISTFILE" "$HISTSIZE" "$HISTFILESIZE".
  • Confirm that HISTFILE exists and is writable by the account.
  • If another SSH shell wrote commands, run history -n.
  • Remember that a newly started shell may not have entries that an existing shell has not appended with history -a.

The history file was overwritten

Enable shopt -s histappend for interactive shells. Without histappend, Bash can overwrite the file when a shell exits, which is especially easy to trigger with multiple concurrent SSH sessions. Recover only from a backup or another surviving shell; Bash cannot reconstruct entries that were overwritten.

An exclamation mark causes an event-not-found error

Use single quotes, escape the mark, or disable expansion with set +H. In a double-quoted string, a backslash is required before !. In scripts, do not assume an interactive shell’s history setting; set the behavior explicitly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A command ran before you could review it

Prefer history followed by an explicit copy, or use fc -e "$EDITOR". History expansion happens before execution, so pressing Enter after typing !! does not provide a confirmation screen.

Timestamps are absent

Set HISTTIMEFORMAT before displaying history and ensure the shell can write its history file. Existing entries may not have timestamp markers; timestamps are recorded as Bash saves entries after the setting is active.

A safe, repeatable workflow

  1. Start by inspecting: run history 20 and identify the exact event.
  2. For a risky command, copy it into an editor or run fc -e "$EDITOR" over the relevant range.
  3. Check paths, hostnames, privilege escalation, redirections, and destructive flags before saving.
  4. Use set +H when entering literal exclamation marks or when expansion could confuse a script-like command.
  5. After meaningful work in a multi-SSH setup, run history -a; before searching for another shell’s work, run history -n.
  6. Never put credentials directly in command arguments. If one was exposed, remove the history entry, rewrite the file, and rotate the credential.

These practices preserve the convenience of Bash history without confusing it with a change-management system or a security log. Bash history is a user-level aid: useful for recalling how you solved a problem, but only as trustworthy and complete as the shell, file, permissions, and filtering choices behind it.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.