Get the Last Argument of the Last Run Command in Your Shell with $_
This came in handy recently when I wanted to automatically cd into a long git clone path without typing the path again.
Quick Jump: Demo Video
I like how after using the command line for years there’s always something new to learn.
Here’s a TL;DR example of how you can avoid typing the same path a few times:
# This will use the /tmp/example-path value in every case of using $_ below: mkdir -p /tmp/example-path \ && git clone https://github.com/nickjj/dotfiles $_ \ && cd $_ \ && rm -rf $_
Now, you could say to make the path a variable and if it were a dedicated script in a file I would agree but using
$_ on the command line once in a while is handy.
For example you might
mkdir -p some/really/long/path and then decide to
mv some_file $_ to move a file to the new directory you just created. By the way, it’s a good idea to quote your variables and I always like using braces in scripts but for ad-hoc commands when you know you don’t need them the shorter
$_ works nicely.
- 0:08 – A couple of practical use cases
- 0:24 – Using it to move a file into a recently created directory
- 1:01 – I’d likely use a variable in a persisted script
- 1:10 – Quotes and braces for ad-hoc commands like this are optional IMO
- 1:39 – What are you going to use this for?
Can you think of another use case where this would be useful? Let me know below.