Terminal replacing ! followed by a number with a command

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.


Solution 1:

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 ('!').