12

I'm very confused about my ubuntu terminal session, it seems to replace sections in commands that start by ! followed by a number with seemingly random commands. It does that with !87 replacing it with screen -l and also with !88 and replaced it with ls.

Any ideas why this is happening would be much appreciated.

20

That's bash's history expansion, e.g.

!87

re-executes the command from history line 87.

You find the description of this feature in man bash, section “HISTORY EXPANSION”:

       An  event  designator  is  a  reference  to a command line entry in the
       history list.  Unless the reference is absolute, events are relative to
       the current position in the history list.

       !      Start  a  history substitution, except when followed by a blank,
              newline, carriage return, = or ( (when the extglob shell  option
              is enabled using the shopt builtin).
       !n     Refer to command line n.
       !-n    Refer to the current command minus n.

So to quickly call the last command, do !-1 and for the fifth last command !-5. A handy synonym for !-1 is !! – if you called e.g. apt install something and forgot the sudo, just execute sudo !! and you're good.

Only backslash (\) and single quotes can quote the history expansion character.

To avoid history expansion, you need to either escape the exclamation mark with a backslash (\!) or use single quotes ('!').

  • 3
    to pass a litereal ! to your commands and avoid history expansion, you'll need to single-quote or escape them: foo '!87' or foo \!87. (double-quotes will also perform the expansion on their contents.) – quixotic Nov 15 '17 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.