Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Special Variables in Linux
2.1.
$$
2.2.
$@
2.3.
$*
2.4.
$#
2.5.
$0
2.6.
$? 
2.7.
$!
2.8.
$-
2.9.
$_
3.
Frequently Asked Questions 
3.1.
What is the use of $n?
3.2.
What are the types of variables in Linux?
3.3.
How to destroy a declared variable? 
3.4.
What is the use of the echo command in Linux? 
3.5.
Which variable will display the list of the positional parameters?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Linux - Special Variables

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

A variable is a place in memory where a value is kept. This place has a name to make it more descriptive. Any sort of data, such as name, number, text, filename, or directory, could be the value. A variable is, therefore, nothing more than a reference to a specific piece of data. A user can create, assign, or delete variables using a shell. These variables, however, are just momentary and are immediately erased when the shell session ends. A shell variable must be exported to become an environment variable and become persistent and system-wide.  

Introduction image

Additionally, Linux has unique variable features. They are used to manage the execution flow of Linux scripts. Their values can be read, but they cannot have values assigned to them. This blog will teach you how to use nine special variables in Linux. So let's investigate today's subject of unique Linux variables. 

Special Variables in Linux

$$

The process ID or PID number of the currently active shell is provided by the $$. This behaves differently depending on whether you use this particular Bash variable from the Linux command line or within the shell script. This is because $$ generates the process ID of the active bash shell. However, a new Bash shell is launched when you start a new script.

Let’s take an example to better understand it. 

$$ output

This gives the PID of the current shell. 

$@

All parameters given to the Bash script are referred to as $@ (dollar at the rate). Every argument receives a double quotation. For instance, the $@ variable represents $1 and $2 when a Bash script is given two parameters.

The first parameter would be connected with the first portion of the word, and the last parameter would be merged with the end part of the entire word. Each positional parameter extends as a separate field. The expansion of the special variable @, even when you double-quote it, results in zero areas if there is no positional argument.

In brief, $@ expands to the arguments passed from the caller to a function or a script. Its meaning is context-dependent: Inside a function, it expands to the arguments passed to such function. If used in a script (outside a function), it expands to the arguments passed to such script.

#!/bin/bash
# special.sh
echo "Process ID of shell = $$"
echo "Program name = $0"
echo "Number of args = $#"
echo "Argument 1 = $1"
echo "Argument 2 = $2"
echo "Complete list of arguments = $*"
echo "Complete list of arguments = $@"

 

$* and $@ are used to get the total number of arguments in the script, and we currently assign 3 arguments, therefore it is printing the arg1, arg2, arg3. 

$*

All variables written as a single string are denoted by the special variable $* (dollar star). The majority of arguments are double-quoted.

$* output

In the above example, we enclosed two distinct pieces in double quotations; (semicolon). Bash combined the two components into a single argument. Bash recognizes the space you type in a Bash client as a separator.

Starting a Bash script allows you to pass arguments. The script deals with the arguments supplied to it. For whatever reason, declaring or not declaring many variables to the Bash script has no effect if the script doesn't handle disputes. $1, $2, and other variables in passing arguments.

$#

In Bash, a unique variable called $# (dollar hash) expands to the decimal value of the positional parameters. The Bash script or total shell number of parameters is contained in the variable $#. Use the following syntax when parameters are given directly. 

bash -c 'echo $#' _ <arg1> <arg2>...


In the example above, Bash -c receives an argument written after a command. Here the _ (underscore) denotes a placeholder. 

Note: The command name (parameter 0) is not included in the number shown by the '#' symbol. This is so that it is clear that "#" is a unique, not a positional, parameter. 

#!/bin/bash

echo $0
echo $1
echo $2
echo $#

 

We first take one argument, and then two argument and then we use $# therefore it print 3, as we have total 3 arguments in the script.

$0

The running script's filename is displayed using the special variable $0. In this case, type: 

echo $0 


This produces the following output.

$0 output

The output shows “bash” as our current script’s filename.

$? 

A unique variable called $? shows the exit code of the most recent command. Once you are aware of a statement's exit code, you can move the script in a number of different directions. Exit codes of zero often indicate that the previous process was terminated successfully. If the exit code is 1 (or more), it frequently denotes that the process came to a halt due to a mistake or a poor result. The order is:  

Echo $?

 

Let’s discuss an example to better understand 

$? output

I successfully ran my final piece of code, so when I ran the command, the output was 0. Then we received the message "rm: can't remove coding. world': No such file or directory." The outcome of this after running the program was 1. Here, we attempted to use the rm command to remove the file "coding.world". But it doesn't appear like coding.world is already present in our shell. This is why we got an error.

$!

A unique variable called $! (dollar exclamation) holds the PID of the most recent job that has been backgrounded. extends to the process ID of the most recent background or asynchronous command. Some parameters are handled differently by the shell. These cannot have values assigned to them; only references are permitted.

The syntax for using the variable 

echo "$!"


 

$! Holds the PID of the most recent job, hence PID is 10492 of the recent job, and when we print it using $! we get the same output

$-

The unique variable $- (dollar hyphen) returns the flags currently utilized in the Bash shell. The shell's active terminal flags are contained in $-. These flags control the behavior of your shell. 

Here is the syntax and its result. 

echo $-

 

$- output

We can see -h, -i, -m, -B, -H, -s flags are active in our current Bash shell. Below are some flags and their meanings.

  • -s: The abbreviation for stdin is -s. This reads stdin commands.
  • -m: The abbreviation for monitor is -m. This makes job control possible.
  • -i: The abbreviation for interactive is -i. It indicates that the active shell is interactive.
  • -n: The abbreviation for noexec is -n. It implies that you cannot execute script commands; you can only read them.
  • -a: The abbreviation for allexport is-a. All declared variables are exported using this.
  • -D: -D does not allow you to run script commands; instead, it displays a list of all double-quoted strings with a $ prefix.
  • -C: Through redirection, it stops you from overwriting files.
  • -B: This makes Bash's brace expansion feature available.

$_

$_ (dollar underscore) is a special Bash variable set to latest argument of the last executed command. 

As for the syntax: 

bash -c 'echo $#' _ x y
echo $_

 

$_ output

You can see from the example above that we passed the two arguments, x and y. Therefore, y is the final parameter of the most recent command to be executed. As a result, when we executed the $ variable, the result was y.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions 

What is the use of $n?

These variables are the same as the arguments used to call a script. The positive decimal number n indicates the location of an argument in this case; the first argument is $1, the second argument is $2, and so on. 

What are the types of variables in Linux?

There are three types of variables i.e. local, environment, and shell variables. 

How to destroy a declared variable? 

We can use the command unset<variable name>. 

What is the use of the echo command in Linux? 

A shell variable is a unique variable set by the shell and is necessary for the shell to operate properly. While others are local factors, some of these variables are environment-related. 

Which variable will display the list of the positional parameters?

$* will display the list of positional parameters. 

Conclusion

We discussed the nine unique Bash variables $$, $@, $-, $_, $?, $0, $!, $*, and $#. These are all distinct from one another and perform various functions. Additionally, we offered examples of how to utilize them in the terminal and their syntaxes. I hope you find the blog useful. 

For Related Blogs, please refer to:

  1. Types of Unix Operating System
  2. Introduction to Linux Shell and Shell Scripting
  3. Ubuntu Operating System
     

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available; look at the Top 150 Interview Puzzles interview experiences, and interview bundle for placement preparations. Read our blogs on aptitudecompetitive programminginterview questionsIT certifications, and data structures and algorithms for the best preparation.

Previous article
rsync command in linux
Next article
Linux - Commands and Arguments
Live masterclass