22

I recently saw a video where someone executed ^foo^bar in Bash. What is that combination for?

Mateusz Piotrowski
  • 4,623
  • 5
  • 36
  • 70
manifestor
  • 2,423
  • 6
  • 22
  • 47
  • 6
    Possible duplicate of [^x^y unix trick for all instances in last command?](https://unix.stackexchange.com/questions/116623/xy-unix-trick-for-all-instances-in-last-command) and [related](https://www.google.fr/url?q=https://stackoverflow.com/questions/2149482/caret-search-and-replace-in-bash-shell&sa=U&ved=0ahUKEwitu4nh4JXYAhXEaFAKHYE1CR8QFggLMAA&usg=AOvVaw1-gSC9hIEU5KIa1bujCNSl) – Julien Lopez Dec 19 '17 at 09:25

2 Answers2

26

Bash calls this a quick substitution. It's in the "History Expansion" section of the Bash man page, under the "Event Designators" section (online manual):

^string1^string2^

Quick substitution. Repeat the previous command, replacing string1 with string2. Equivalent to !!:s/string1/string2/

So ^foo^bar would run the previously executed command, but replace the first occurence of foo with bar.

Note that for s/old/new/, the bash man page says "The final delimiter is optional if it is the last character of the event line." This is why you can use ^foo^bar and aren't required to use ^foo^bar^.

(See this answer for a bunch of other designators, although I didn't mention this one there).

Wildcard
  • 35,316
  • 26
  • 130
  • 258
Michael Mrozek
  • 91,316
  • 38
  • 238
  • 232
15

^foo^bar executes that last command, replacing the first instance of foo with bar. For example:

$ ech "hello"
-bash: ech: command not found
$ ^ech^echo
echo "hello"
hello
Timothy Pulliam
  • 3,549
  • 3
  • 21
  • 42