Variables are the essential part of programming, or we can say that they are the spirit of a programming language. Variables specify the memory location through characters, numeric, and alphanumeric. They are used to be referenced and manipulated in a computer program.
What are the variables?
Variables are the containers which store data or a useful piece of information as the value inside them. Below is the syntax for a variable:
A Variable is a combined form of two words, i.e., vary + able, which means its value can be changed, and it can be used for multiple times.
Variable is known as the temporary storage for any kind of data like integer, float, char, etc. A variable name can include alphabets, digits, and underscore, and its name can be started with alphabets and underscore only.
Note: We cannot define a variable name starting with any digit.
What are Bash Variables?
We cannot use bash variables without having the proper information (syntax, data types, types, working) about it, so, let’s go throughout this brief tutorial for having the appropriate overview of Bash Variables.
At first, know the syntax.
Rules Set for Defining Bash Variables:
- Prefix the variable name with dollar ($) sign while reading or printing a variable.
- Leave off the dollar sign ($) while setting a variable with any value.
- A variable name may be alphanumeric, or it may be written with an underscore (_).
- A variable name is case-sensitive: x and X are considered as two different variables.
- variable name can be written either in UPPER_CASE or LOWER_CASE letters or mixture of both as you want.
- A variable can be placed at anywhere in a Bash Script or on the command line, because on runtime, Bash will replace it with its assigned value. It became possible because of doing substitution before running the command.
- There should not be whitespace on either side of the equal sign (=) between the variable name and its value. Following are some example of Invalid Variables having whitespaces (denoted by dots …) between them as given below:
- There is no need of using any quotes, either single or double, to define a variable with single character value such as var1=variable. To input multiple words or String as a single item in a variable, then make use of quotes for enclosing your content in that variable.
- Single Quote (”) helps to treat every character.
- Double Quote (“”) helps to do the substitution.
In the formal programming languages, you have to define the data type of any variable at the time of variable declaration. For example:
But in case of Bash, you don’t have to define the data type of any variable at the time of variable declaration. Bash variables are untyped, which means just type the variable name by assigning its value, and it will automatically consider that data type.
Such that if you assign any numeric value to the variable, it will work as integer and if you assign a character value to the variable, then it will be String.
using echo command, read them by assigning $ sign before their name such as
Types of Bash Variables
There are two types of variables in a shell or any UNIX system.
- System-Defined Variables
- User-Defined Variables
1. System-Defined Variables: These are the pre-defined variables as they are created and maintained by the LINUX operating system itself. Their standard convention is that generally they are defined in capital letters, i.e., UPPER_CASE. So whenever you see a variable defined in upper cases, most likely, they are the system-defined variables.
These are the following System-defined variables as given below:
1. BASH represents the Shell Name.
2. BASH_VERSION specifies the shell version which the Bash holds.
3. COLUMNS specify the no. of columns for our screen.
4. HOME specifies the home directory for the user.
5. LOGNAME specifies the logging user name.
6. OSTYPE tells the type of OS.
7. PWD represents the current working directory.
8. USERNAME specifies the name of currently logged in user.
To know the list of these variables in your system, type the commands set, env, and printenv on the command line terminal as follows:
1. Typing the set command.
2. Typing the env command
3. Typing the printenv command
Let’s call these variables through Bash Shell. Following are the given steps:
Step 1: Create a script named by Bash_sdvar and type the following code on the Bash Console as follows:
Step 2. Look at the Bash Console given below:
Step 3. Save and execute the script. It will show the output as you can see in the figure given below.
2. User-defined Variables: These variables are created and maintained by the user. Generally, these types of variables are defined in LOWER_CASES. There is not any strict rule to write these variables in lower-cases. We can write them in upper-cases also.
Let’s create a Bash Script to define these variables. Follow the given steps given below:
Step 1. Create a script named by Bash_udvar and type the following code on Bash Console:
Step 2. See the code on Bash Console.
Step 3. Save and execute the Script.
Working of Bash Variables
After having a basic demonstration of variables, let’s move to know how do they work?
There are two actions we usually perform for a variable in Bash as given below:
- setting a value for a Variable
- reading the value for it.
A variable value can be set in different ways in which the most common way is to set the value directly. To read a variable, we can place its name (prefixing with $ sign) anywhere in the script.
Bash first checks all the variable names as if they are present in the script. Then it interprets every line of our script. After identifying every variable, it replaces a variable name with its assigned value. After all, it interprets/runs that line of code and continues this process for every coded line of our script.
NOTE: Both the kinds of variables in Bash (we discussed) work on the terminal as well as on Bash script. Let see their working on terminal and Bash through a straightforward example:
Example: Call a user name by XYZ, his location at which he is currently working, and the version of Bash Shell he is using for Bash Scripting.
1. Working On Terminal
2. Working on Bash Shell
See the script named by Bash_Var given below:
In the 3rd line of the script, we declared a variable USER_NAME to store the user name XYZ as its value.
In the last two lines, we have printed the intended message by using the echo command.
There are two variables and one command in this message. Each one of them is preceded by the dollar ($) sign where:
- USER_NAME is a user-defined variable to call the user name,
- BASH_VERSION is system-defined variable, which shell calls itself. It is used to print the version of Bash Shell,
- PWD command is used to print the current location of the user.
For better understanding, create this script by following the given code:
It will show the output as you can see in the following image:
There are some more examples for practicing variables on both terminal and Bash Shell. By following the rule set (discussed before) have a practice on variables as follows:
A. Using Command Line Terminal
1. Setting the variables
2. Reading and referencing the variables
3. Invalid Variables
4. Combining two string variables
5. Concatenating Strings with variables
NOTE: Don’t use single quotes for combining two variables and also for concatenation of Strings with variables. Such that if you concatenate Strings by enclosing them in single quotes, then it will be a failure to read them as you can see in the image given below:
B. Using Bash Script:
It is an example of combining the String variables.
Command line Arguments
Command Line Arguments are used to make a script more dynamic by passing input to the code. We pass these arguments at the runtime of the script as the following form:
There should be no space between the script name and all the passing arguments.
How to use command line arguments?
In a Bash Shell, they are used with the reference of the following default-parameters or the special variables.
- $0 specifies the name of the script to be invoked.
- $1-$9 stores the names of the first 9 arguments or can be used as the arguments’ positions.
- $# specifies the total number (count) of arguments passed to the script.
- $* stores all the command line arguments by joining them together.
- [email protected] stores the list of arguments as an array.
- $? specifies the process ID of the current script.
- $$ specifies the exit status of the last command or the most recent execution process.
- $! shows ID of the last background job.
Following are the two methods we use for passing command line arguments:
Method 1: Using Position number
It is the first way of accessing the arguments by using the default parameters ($1…$9). Below image explains it:
Method 2: Using Array.
It is the second way of passing the arguments as an Array. Follow the given algorithm to apply this method.
Step 1: Create a Bash Script.
Step 2: Declare any variable name and assign its value as $a in the following form:
Where [email protected] is the default argument which is used to store the arguments (we pass) as an array.
Step 3: Display the arguments by defining their array index in the following form:
Step 4: Save and close the Script.
Step 5: Execute the Script by passing the arguments.
See the following program:
On Bash Console:
According to the Bash Official Documentation
“Command Substitution allows the output of a command to replace the command itself. Bash performs the expansion by executing the command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.”
Command substitution refers to an expansion which Bash performs for us. It takes the output of the Bash command, stores in a variable (generally), and display back with echo.
Command Substitution offers data flexibility in regards to scripting and variable assignment. It is simple and easy for having the single command line output. In case, the output goes over a few lines, then the newly trailing lines are removed, and the full content of output ends up on a single line.
See the syntax for use:
The classic form of substituting commands in a variable or command substitution is using backquotes (`…`), as given below:
Now, we do command substitution by enclosing the commands within brackets (preceded by the dollar sign ($)). Have a look:
So, let’s do command substitution with an example as per the discussion.
In this example, we are substituting single command ls in a variable. See the terminal.
Line 1: Without command substitution, the output is expanded in multiple lines.
Line 2 and 3: With command substitution, the output is ended on a single line (saved space by removing newly trailed lines).
Following is the Bash Script to test the command substitution.
See the Bash Console: