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?

  • Hi, you can try to use fc command , fc -rl | awk '{ print $2 }' | head -1 – Edouard Fazenda Jan 19 '15 at 10:44
  • !:0 will give you word 0 (the command word itself) of the previous command. – PM 2Ring Jan 19 '15 at 10:46
  • And if you want to see the command produced by history expansion before hitting Enter you can use the shell-expand-line key sequence M-C-e, that is Meta-Ctrl-e; Meta is usually Alt. – PM 2Ring Jan 19 '15 at 10:51

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
  • Second comment under my question mentions: !:0, what is the difference between !:0 and !!:0? – syntagma Jan 19 '15 at 10:47
  • You can use !:0, and note in bash, if extglob is enabled, it must not follow by blank, newline, \r, = or (. – cuonglm Jan 19 '15 at 10:48
  • 1
    @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. – jimmij Jan 19 '15 at 10:52
  • 1
    You don't need to echo. You can use the p modifier instead: !!:0:p – muru Jan 19 '15 at 10:55

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).


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.