Home > Bash, Tip > Make use of bash variable $_

Make use of bash variable $_

I’ve discovered recently that you can use $_ to access the last argument in the last command that you type in bash. For example, you run this command

$ cat /usr/local/bin/myscript.sh

the screen will display the content of the file /usr/local/bin/myscript.sh, which you wish to edit now. The old (and I believe most of us still do) way to do is to scroll up with the up arrow key, move cursor right after cat and replace it with your editor (say, vi), now the new command becomes

$ vi /usr/local/bin/myscript.sh

Hit enter and you will be able to edit the file (assuming you have write access to myscript.sh)

It’s working well but not that well when you can do it in a better way:
right after the cat command, try the following instead:

$ vi $_

this will substitute $_ with the last argument (which is /usr/local/bin/myscript.sh), clean and efficient. [ I am not saying cat a file then edit it is the most efficient way, but the above is to demonstrating the usage of $_ and I hope you find this tip useful.]

Advertisements
Categories: Bash, Tip
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: