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