Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

🍿 Run shell command with previous command's arguments

Snacks (🍿) are my collection of recipes for solving problems. Often recorded (and cleaned up) from actual discussions where I'm involved in helping others with technical problems. Not all solutions are mine but I started collecting them in one place because you never know when you need one.

I have this workflow where after I've written some code, I run

git diff src/components/Alpha/

to check that I haven't forgotten any debug messages or weird formattings or anything else like that. I then follow up with

git add src/components/Alpha/

and sometimes the path becomes long and its arduous to write, even with path autocomplete.

Finally today I decided to figure out a way to avoid that.

I was already familiar with !! that replicates the previous command and I knew of ![n] that replicates the nth last from history. But I didn't know how to run different commands with same arguments.

That can be done with one of these

git diff src/components/Alpha/
git add !$ # run with the last argument from previous command
git add !* # run with all the arguments from previous command
git add !:n # run with the nth argument 

Looking at it with a simplified example:

echo 1 2 3 4
echo $! # -> echo 4
echo 1 2 3 4
echo $* # -> echo 1 2 3 4
echo 1 2 3 4
echo $:3 # -> echo 3