Difference between $_ and $- variables in Linux
What is $_ variable in Linux
The $_ in bash is a special variable that holds the last argument of the previous command. This is particularly useful when you want to repeat the last command or argument without having to retype it.
For example, if you were to use the ls command to list files in a directory, and you wanted to use the cd command to navigate into that directory, instead of typing the directory name again, you could use $_:
ls /path/to/directory
cd $_In this example, $_ would be replaced with /path/to/directory, effectively changing the working directory to the last listed directory.
Get Linux Root Room’s stories in your inbox
Join Medium for free to get updates from this writer.
It’s worth noting that $_ is a shell built-in variable and it gets updated after every command execution. So, it's always holding the last argument of the most recent command.
What is $- Variable in Linux
The $- in bash is a special variable that holds the current set of options in your current shell. Each character in the string represents a different option. For example, himBH means following options are enabled:
h- histexpand: when history expansion is enabledi- interactive: when current shell is interactivem- monitor: when job control is enabledB- braceexpand: when brace expansion is enabledH- hashall: Locate and remember (hash) commands as they are looked up for execution
You can print the current set of options by simply typing echo $- in your terminal.
Example — A Linux shell script that uses $- variable
In this video, a shell script is written, which shows that each shell script is executed by a non-interactive shell with the help of $- variable and case condition.
Read more about video above: link
Difference between $_ and $-
The $_ and $- are both special variables in bash, but they serve different purposes:
$_(underscore): This variable holds the last argument of the previous command. It's particularly useful when you want to reuse the last argument of a command without having to retype it.$-(dash): This variable holds the current set of options in your current shell. Each character in the string represents a different option. For example,himBHmeans following options are enabled: histexpand, interactive, monitor, braceexpand, hashall.
So, the main difference between $_ and $- is that $_ refers to the last argument of the previous command, while $- refers to the current set of shell options.
Read More
My YouTube Channel
More shell script videos and linux tutorials on my YouTube Channel.







