Home Linux Tips & TricksEasy Ways To Insert The Last Argument Of The Previous Command In Bash, Fish and Zsh

Easy Ways To Insert The Last Argument Of The Previous Command In Bash, Fish and Zsh

Smart Shell Tips: Reuse Arguments Without Retyping in Linux

By sk
751 views 8 mins read

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!

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 $_ opens notes.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:

  1. Type your command: mkdir my-project
  2. Press Enter to run it
  3. Start typing: cd
  4. Press Alt + . (or Esc + .)
  5. 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:


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?

MethodBest ForWorks in ScriptsCan Edit Before Running
$_Scripts, automation✅ Yes❌ No
!$Quick interactive use✅ Yes❌ No
Alt+.Interactive typing❌ No✅ Yes
FunctionsRepeated tasks✅ Yes❌ No
VariablesComplex 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.
Insert Last Argument of the Previous Command in Linux
Insert Last Argument of the Previous Command in Linux

Summary: $_ vs !$

Feature$_!$
TypeShell variableHistory expansion
TimingAfter command runsBefore command runs
Use caseScripts, safe reuseQuick typing shortcuts
Reliable?Yes, in scriptsNo, can break with complex commands
Examplemkdir 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 like if, {}, 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

Q: Does 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.

Q: Can I use these in scripts?

A: Use $_ in scripts. Avoid !$, since it expands from history and may behave unpredictably.

Q: What about Fish shell?

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:

You May Also Like

1 comment

Naibed June 25, 2025 - 9:38 pm

Just a reminder that w/ `!?`, you can edit it b4 running via `Ctrl + Alt + e`

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More