Do you type the same file names or folder paths over and over in your terminal? There's a much easier way! In this guide, you'll learn different methods to insert the last argument of your previous command in Bash, Fish and Zsh. No Retyping, No Errors!
Learning how to reuse the last argument from your previous command can save you time and prevent typing mistakes.
All of these tricks should work in Bash. Some may work in Fish, Zsh and other shells. Let's get started!
Table of Contents
What is the Last Argument?
The last argument is the final word or parameter in a command. For example:
mkdir /home/user/my-long-project-name
Here, /home/user/my-long-project-name
is the last argument. Instead of typing this long path again, you can reuse it automatically.
Method 1: Insert Last Argument of the Previous Command using $_
Variable
The $_
variable is the easiest way to grab the last argument from your previous command.
Example 1:
mkdir project-folder cd $_
This creates a folder called "project-folder" and then moves into it. The $_
automatically becomes "project-folder".
Example 2:
cp /var/log/nginx/access.log /tmp/backup/ ls -la $_
This copies a log file to a backup folder, then lists the contents of that backup folder. No need to type the long path twice!
Example 3:
touch notes.txt && nano $_
touch notes.txt
creates a file.nano $_
opensnotes.txt
in the Nano editor.
This works well when you chain two commands.
When to Use $_
- Perfect for scripts and automation.
$_
is safe to use in scripts because it only expands after the last command runs. - Works in all major shells.
- Most reliable method for file operations.
Method 2: Reuse Last Argument of Previous Command using !$
The !$
is a history expansion that grabs the last argument from your previous command. Please note that !$
shortcut works before your next command runs, unlike $_
, which works after.
Example 1:
touch important-document.txt vim !$
This creates a file and then opens it for editing. The !$
becomes "important-document.txt".
Example 2:
wget https://example.com/large-file.zip -O file.zip unzip !$ rm !$
This downloads a file, extracts it, and then deletes the original zip file.
When to Use !$
- Great for interactive terminal use.
- Quick and easy to type.
- Works well with simple commands.
!$
doesn’t always work well in scripts or with complex commands.
Safety Tip: Use the following command to enable history verification to see what
!$
will expand to:
shopt -s histverify
Method 3: Insert Last Command Argument using Alt+.
Keyboard Shortcut
The Alt+.
keyboard shortcut inserts the last command's argument right where your cursor is.
How to Use it:
- Type your command:
mkdir my-project
- Press Enter to run it
- Start typing:
cd
- Press
Alt + .
(orEsc + .
) - It automatically inserts "my-project"
The Cycling Feature
Press Alt + .
multiple times to cycle through previous arguments:
git add file1.txt git commit -m "Added new feature" git push origin main cd Alt+. # Shows "main" cd Alt+. Alt+. # Shows "Added new feature"
When to Use Alt+.
- Best for interactive typing.
- You can see the text before running the command.
- Perfect when you need to edit the argument.
Method 4: Create a Custom Function
For common tasks like creating and entering directories, make your own function:
mkcd() { mkdir -p "$1" && cd "$1"; }
Add this to your .bashrc
file, then use it like this:
mkcd new-project
This creates the directory and moves into it with one command.
More Useful Functions
# Create and edit a file touchedit() { touch "$1" && vim "$1"; } # Copy and then list the destination cpls() { cp "$1" "$2" && ls -la "$2"; }
Related Read:
- How To Manage Bash Functions Using declare Command In Linux
- How To Manage Functions In Fish Shell On Linux
Method 5: Using Variables
For very long paths or complex arguments, save them in variables:
logfile="/var/log/application/debug-$(date +%Y%m%d).log" tail -f "$logfile" vim "$logfile"
This approach works great when you need to use the same long path multiple times.
Related Read:
Pro Tips for Power Users: Combine Multiple Methods
mkdir long-project-name cd $_ # Runs cd long-project-name touch readme.md vim Alt+. # Shows "vim readme.md"
Comparison Table: Which Method to Choose?
Method | Best For | Works in Scripts | Can Edit Before Running |
---|---|---|---|
$_ | Scripts, automation | ✅ Yes | ❌ No |
!$ | Quick interactive use | ✅ Yes | ❌ No |
Alt+. | Interactive typing | ❌ No | ✅ Yes |
Functions | Repeated tasks | ✅ Yes | ❌ No |
Variables | Complex arguments | ✅ Yes | ✅ Yes |
Difference between $_
and !$
in Bash
The difference between $_
and !$
in Bash is subtle but important. Both refer to the last argument of a previous command, but they behave differently depending on how the shell processes history and execution.
$_
: The Last Argument of the Last Executed Command
$_
is set after the last command runs.- It holds the last argument that was actually used by the shell.
- It’s available as a shell variable.
!$
: The Last Argument of the Last Typed Command
!$
is part of history expansion.- It means: “take the last argument from the previous command I typed.”
- It is expanded before the command runs.
Examples
Let’s walk through a practical example.
$ echo one two three one two three
Now try $_
:
$ echo $_ three
$_
shows three
, the last word used in the last command.
Now run the same echo
command again:
$ echo one two three one two three
Then try the !$
:
$ echo !$
!$
also becomes three
, because it refers to the last word typed in the previous command.
But here’s a case where they differ:
$ { echo A; echo B; } A B
Now try:
$ echo $_ B
$_
shows B
, because that was the last word that actually ran in the previous command block.
Let us try the same command again:
$ { echo A; echo B; } A B
But running:
$ echo !$
gives the unexpected output:
echo }
}
See? !$
gets the last word (i.e. }
) from the previous command and simply prints it.
Because:
!$
tries to expand based on what you typed:{ echo A; echo B; }
.- The shell may not treat the last word (
}
) correctly due to parsing quirks.
Summary: $_
vs !$
Feature | $_ | !$ |
---|---|---|
Type | Shell variable | History expansion |
Timing | After command runs | Before command runs |
Use case | Scripts, safe reuse | Quick typing shortcuts |
Reliable? | Yes, in scripts | No, can break with complex commands |
Example | mkdir dir && cd $_ | mkdir dir , then cd !$ |
When to Use What?
- Use
$_
in scripts or reliable one-liners. - Use
!$
at the prompt when quickly recalling a filename or argument. - Avoid
!$
with complex command structures likeif
,{}
, or pipes.
Common Mistakes to Avoid
1. Forgetting Quotes
Always put quotes around variables with spaces:
# Wrong - will cause errors file="my document.txt" cat $file # Right - handles spaces correctly cat "$file"
2. Using !$
in Scripts
The !$
method doesn't work reliably in scripts. Use $_
instead:
#!/bin/bash # This might not work as expected mkdir project && cd !$ # This works reliably mkdir project && cd $_
3. Not Checking What You're Getting
With Alt+.
, you can see the text before running it. This prevents mistakes:
rm important-file.txt # Later, you want to restore it git checkout Alt+. # You see "git checkout important-file.txt" before running
Real-World Examples
1. Web Development
# Download a project git clone https://github.com/user/awesome-project.git cd $_ # Start the development server npm install npm start
2. System Administration
# Check a log file tail -f /var/log/apache2/error.log # Edit the same file sudo vim $_
3. File Management
# Find a file find /home -name "*.pdf" -type f # Copy the found file cp $(find /home -name "*.pdf" -type f | head -1) /tmp/ ls -la $_
Troubleshooting Common Issues
Command Not Found
If !$
doesn't work, history expansion might be disabled:
set +H # Disable history expansion set -H # Enable history expansion
Alt+. Not Working
Try these alternatives:
Esc + .
(especially on Mac)- Check your terminal's key bindings
- Make sure you're using Bash or Zsh
$_ Shows Wrong Value
The $_
variable gets updated by each command. Make sure you're using it immediately after the command you want:
mkdir test echo "hello" # This updates $_ cd $_ # This will try to cd to "hello", not "test"
Cheatsheet
Here's the cheatsheet of all the methods that we discussed in the previous sections. Print it out and keep it near your desk for quick reference.
# Method 1: $_ variable mkdir folder cd $_ # Method 2: !$ history expansion touch file.txt vim !$ # Method 3: Alt+. keyboard shortcut mkdir project cd [Alt+.] # Method 4: Custom function mkcd() { mkdir -p "$1" && cd "$1"; } # Method 5: Variables path="/long/path/to/file" cp "$path" /backup/ && ls "$path"
FAQs
Alt + .
work in all shells?A: It works in Bash, Fish and Zsh, but some terminal apps may need special settings to use Alt-based shortcuts.
A: Use $_
in scripts. Avoid !$
, since it expands from history and may behave unpredictably.
A: Fish doesn’t support $_
or !$
, but it has interactive suggestions and lets you recall arguments using Alt + ↑
.
Conclusion
Learning to reuse the last argument from previous commands is a quite useful for terminal productivity. Here's what to remember:
- Use
$_
for scripts and reliable automation - Use
!$
for quick interactive commands - Use
Alt+.
when you want to see and edit before running - Create functions for tasks you do often
- Use variables for complex or repeated arguments
Start with the method that works best for you. As you get comfortable, try the others. Soon, you'll wonder how you ever worked without these time-saving tricks.
The best part? These methods work together. You can combine them to create powerful workflows that make your terminal work faster.
Try one of these methods right now in your terminal. Create a test directory and practice moving into it using $_
or Alt+.
. Once you start using these tricks, you'll never want to type the same arguments twice again!
Recommended Read:
1 comment
Just a reminder that w/ `!?`, you can edit it b4 running via `Ctrl + Alt + e`