gotchabashMinor
History expansion gotchas: ! in double-quoted strings and scripts
Viewed 0 times
history expansionbangexclamation markevent not foundinteractive shellhistexpand
Error Messages
Problem
An exclamation mark inside double quotes triggers history expansion in interactive bash shells, causing 'event not found' errors or unexpected command substitution. This catches developers embedding ! in strings.
Solution
In scripts, history expansion is disabled by default — not a concern. In interactive shells:
# These trigger history expansion in interactive bash
echo "hello!"
echo "it's done!"
# Fixes:
echo 'hello!' # single quotes disable all expansion
echo "hello"'!' # concatenate single-quoted !
set +H # disable history expansion in current shell
# In .bashrc to permanently disable:
set +o histexpand
# These trigger history expansion in interactive bash
echo "hello!"
echo "it's done!"
# Fixes:
echo 'hello!' # single quotes disable all expansion
echo "hello"'!' # concatenate single-quoted !
set +H # disable history expansion in current shell
# In .bashrc to permanently disable:
set +o histexpand
Why
History expansion is an interactive shell feature (histexpand option). It's enabled by default in interactive bash but disabled in scripts. The ! character in double quotes is interpreted as the history expansion operator.
Gotchas
- History expansion is ONLY active in interactive shells — not in scripts (#!/usr/bin/env bash)
- set +H or set +o histexpand disables it for the current session
- zsh uses ! for history expansion too, but handles it slightly differently
- HISTIGNORE and HISTCONTROL control what gets recorded but don't affect expansion
- The sequence !! expands to the last command, !$ to the last argument — useful interactively
Code Snippets
History expansion workarounds
# In interactive bash (NOT in scripts):
# BAD: triggers history expansion
echo "hello world!"
# bash: !: event not found
# FIX 1: single quotes
echo 'hello world!'
# FIX 2: string concatenation
echo "hello world"'!'
# FIX 3: disable history expansion
set +H
echo "hello world!"
set -H # re-enable if needed
# FIX 4: escape (works but looks odd)
echo "hello world\!"Context
Interactive bash sessions with exclamation marks in strings
Revisions (0)
No revisions yet.