How to quickly change the first word in a Bash command?

!$ expands to the last word of your previous command.

So you could do:

cat foo/is/a/very/long/path/to/bar.c

rm !$

or:

git diff foo/bar.c

git checkout !$

Your examples happened to only repeat the last word, so !$ worked fine. If you actually had a lot of arguments that you wanted to repeat, and you just wanted to change the first word, you could use !*, which expands to all words of the previous command except the zeroth.

See the "HISTORY EXPANSION" section of the bash man page. There's a lot of flexibility there.


Ctrl+a to go to the beginning of the line, then Alt+d to delete the first word.


I'm not sure if it would actually be faster or not, but see this article, particularly point #.3:

  1. Replace a string from the previous command using ^str1^str2^

In the following example, first we executed the ls command to verify a file. Later we realized that we want to view the content of the file. Instead of typing the whole file name again, we can just replace the “ls” in the previous command with “cat” as shown below.

$ ls /etc/cron.daily/logrotate

$ ^ls^cat^
cat /etc/cron.daily/logrotate

Alt+.

If you need only to repeat the last part of one of the previous commands you can use Alt+. that will paste the last argument taken from the last line of the history.

If pressed more than one time will substitute what just pasted with the last argument of the line before...

E.g. if the last 2 commands were:

cat foo/is/a/very/long/path/to/bar.c
pico foo/is/a/very/long/path/to/SomeWhereElse.c

In the shell I write rmand I press Alt+. it will appear:

rm foo/is/a/very/long/path/to/SomeWhereElse.c

if I press again Alt+. it will appear instead

rm foo/is/a/very/long/path/to/bar.c

and so on...


In addition to @jjlin answer, you might be interested by the following tips:

  • Ctrl+w deletes the word to your left
  • Ctrl+k deletes from cursor to the end of command line
  • Ctrl+u deletes from cursor to the start of command line
  • Alt+b moves cursor one word backward
  • Alt+f moves cursor one word forward
  • $_ contains last argument of the previous command line

For more about these, lookup "Readline Command Names" section of the bash manpage.

eg:

cat foo/is/a/very/long/path/to/bar.c
rm $_