The Cookie Machine - Click here to drag window

DUMMY TEXT - Real text set in assets/js/theCookieMachine.js

If you can read me, I'm broken!

Views: 6,105β€…    Votes:  14β€…
Tags: command-line   bash  
Link: πŸ” See Original Question on Ask Ubuntu ⧉ πŸ”—

Title: What is the purpose of the special parameter "_" (single underscore) in environment?
ID: /2019/12/27/What-is-the-purpose-of-the-special-parameter-___-_single-underscore_-in-environment_
Created: December 27, 2019    Edited:  June 12, 2020
Upload: December 3, 2023    Layout:  post
TOC: false    Navigation:  false    Copy to clipboard:  false

I’m trying to understand how the environment variable _ can be used. Below is an example of using it:

$ echo $_

$ echo $_

$ ls non-existant-filename
ls: cannot access 'non-existant-filename': No such file or directory

$ echo $_

This might be a handy variable for bash scripts but only if it’s function is fully understood.

Some useful applications of _

I found some useful applications of _.

_ contains the last filename you can recycle

In this example _ is used to keep the last filename which you can reuse in subsequent commands without retying it.

$ ll ~/python/
-rwxrwxrwx 1 rick rick 2384 Dec 27 09:15 /home/rick/python/*

$ $_
# The python program ~/python/ is executed

$ cat $_
#!/usr/bin/env python
# -*- coding: utf-8 -*-
   (... SNIP ... remaining contents of ~/python/ appears on screen)

So the $_ variable/parameter can save some typing.

_ contains the last program run

Here’s an example of differences between env and printenv updating the _ variable/parameter:

$ env > env.txt

$ printenv > printenv.txt

$ diff env.txt printenv.txt
< _=/usr/bin/env
> _=/usr/bin/printenv

Because a parameter wasn’t passed to either command, the _ isn’t updated with the last used parameter as in the previous example but, it is updated with the last command used.

Also noticed how _ is updated before the commands env and printenv are executed because _ it appears in the output.

⇧ RPI4 Ubuntu 19.10 64bit Temperature Monitoring How do I save terminal output to a file?  β‡©