How do I get command name of the last executed command?

6,515

Solution 1

You can select particular word from last typed command with !!: and a word designator. As a word designator you need 0. You may find ^ and $ useful too. From man bash:

Word Designators

0 (zero) The zeroth word. For the shell, this is the command word.

^ The first argument. That is, word 1.

$ The last argument.

So in your case try:

echo !!:0

Solution 2

In interactive mode, the easiest way to do this is just a keystroke combination alt+0 and alt+.. The shortcut alt+. means "recall n-th word from the previous line" (by default the last one) and alt+0 gives it an argument 0.

This should work for interactive bash on most systems (more generally, all shells that use readline as its input library).

https://stackoverflow.com/questions/4009412/bash-how-to-use-arguments-from-previous-command

Share:
6,515

Related videos on Youtube

syntagma
Author by

syntagma

Updated on September 18, 2022

Comments

  • syntagma
    syntagma almost 2 years

    Example: I type man ls, than I want to get man only.

    By using !! I can get man ls but how do I get man?

    • Edouard Fazenda
      Edouard Fazenda over 9 years
      Hi, you can try to use fc command , fc -rl | awk '{ print $2 }' | head -1
    • PM 2Ring
      PM 2Ring over 9 years
      !:0 will give you word 0 (the command word itself) of the previous command.
  • syntagma
    syntagma over 9 years
    Second comment under my question mentions: !:0, what is the difference between !:0 and !!:0?
  • cuonglm
    cuonglm over 9 years
    You can use !:0, and note in bash, if extglob is enabled, it must not follow by blank, newline, \r, = or (.
  • jimmij
    jimmij over 9 years
    @REACHUS ! starts history substitution and !! refer to previous command. Probably single ! in some cases denotes !! and indeed echo !:0 works but echo ! doesn't while !! works in both cases.
  • muru
    muru over 9 years
    You don't need to echo. You can use the p modifier instead: !!:0:p