4

Why does this command line work:

$ output='Irrelevant'; if [[ $output =~ Something ]]; then echo "I found something in the output." ; fi

And this one give me a strange parse error?

$ output='Irrelevant'; if [[ $output =~ Something ]]; then echo "I found something in the output!" ; fi
-bash: !": event not found

The only change from the first version is that the sentence to be echoed inside quotes ends with an exclamation mark. Why does Bash give me that error in the second version?

In case it matters, this is the output from bash --version:

GNU bash, version 4.2.24(1)-release (x86_64-pc-linux-gnu)
codeforester
  • 39,467
  • 16
  • 112
  • 140
Deleted
  • 4,067
  • 6
  • 33
  • 51

1 Answers1

7

You can wrap the string in single quotes instead of double quotes.

The exclamation point invokes the very useful history expansion function described in the bash manual.

History expansions are introduced by the appearance of the history expansion character, which is ! by default. Only \ and ' may be used to escape the history expansion character.

For instance, to execute the last command that started with the word mysql type this:

!mysql

or to execute the last command containing the word grep, type this:

!?grep

The bash manual also documents the syntax of the history expansion operators.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
jspcal
  • 50,847
  • 7
  • 72
  • 76