Linux Tips & Tricks · October 7, 2021

Calling previous parameter in Bash

[Linux] Use Previous Parameter In The Next Command

Sometimes you write a command parameter relatively long. Usually, an absolute path. And sometimes, you may want to use that parameter again. Who’s going to write that again…

I’ve tried this in my main shell, Bash. But I’m sure other shells have this trick too.

How to call previous parameter in Bash?

You can use “!$” to call the parameter from previous command. Let’s say we’re searching for a special directory to work on it. And we checked the ownership and permissions of that specific directory. Bingo! We found it. Now we need to change directory into that directory and keep working inside.

The example below shows that scenario. We’re looking a directory’s permissions. And then we decide to cd in it. By calling “cd !$“, we’re calling the parameter from previous command, which was “ls -ld“:

ali@zion:~$ pwd
/home/ali
ali@zion:~$ ls -ld /usr/src/linux-headers-5.11.0-37-generic/kernel/time/
drwxr-xr-x 2 root root 4096 Eyl 29 09:04 /usr/src/linux-headers-5.11.0-37-generic/kernel/time/
ali@zion:~$ cd !$
cd /usr/src/linux-headers-5.11.0-37-generic/kernel/time/
ali@zion:/usr/src/linux-headers-5.11.0-37-generic/kernel/time$ pwd
/usr/src/linux-headers-5.11.0-37-generic/kernel/time

Here’s another example. We’re using mkdir to create a directory. Later, we’re copying a file into that directory without giving it’s path, because we can call latest parameter with !$:

[root@localhost ~]# ls
anaconda-ks.cfg  wget-1.14-18.el7_6.1.x86_64.rpm
[root@localhost ~]# mkdir -p /opt/rpm_packages/please_install_me_later
[root@localhost ~]# cp wget-1.14-18.el7_6.1.x86_64.rpm !$
cp wget-1.14-18.el7_6.1.x86_64.rpm /opt/rpm_packages/please_install_me_later
[root@localhost ~]# ls -l !$
ls -l /opt/rpm_packages/please_install_me_later
total 548
-rw-r--r--. 1 root root 560272 Eki  7 20:54 wget-1.14-18.el7_6.1.x86_64.rpm
Calling previous parameter in Bash
Calling previous parameter in Bash