Assume that the history list contains the command e='echo a b c' and then $e.

How to refer to the command $e using the history expansion feature of bash?

  • @AdminBee !$ refers the last word of the last command. If $e is not the last command, !$ does not work.
    – tmpbin
    Jul 10, 2020 at 12:34
  • You are right; showcase of a bad testing example :(
    – AdminBee
    Jul 10, 2020 at 12:35
  • This works for your example: !?$, but it searches $anywhere in the command, not only in the beginning. So if there is some other command with $ e.g. echo "$e" coming after $e ..., you get that.
    – pLumo
    Jul 10, 2020 at 13:20

1 Answer 1


Here is an alternative you can set an alias for:

eval `history |awk '/^  [0-9]*  [$]/{print $2}'|tail -n 1`

It searches the history for the last command starting with $ and evaluates the result. Although, it will not work with multiline commands.

I would suggest using Ctrl+R, typing $, and cycling through previous commands matching $.

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.