Javatpoint Logo
Javatpoint Logo

Bash Variables

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.

Syntax:

Rules Set for Defining Bash Variables:

  1. Prefix the variable name with dollar ($) sign while reading or printing a variable.
  2. Leave off the dollar sign ($) while setting a variable with any value.
  3. A variable name may be alphanumeric, or it may be written with an underscore (_).
  4. A variable name is case-sensitive: x and X are considered as two different variables.
  5. variable name can be written either in UPPER_CASE or LOWER_CASE letters or mixture of both as you want.
  6. 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.
  7. 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:
    var1=...variable1
    var2...=variable2
    var3...=...variable3
  8. 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.

Data Types

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

echo $year
echo $name

Types of Bash Variables

There are two types of variables in a shell or any UNIX system.

  1. System-Defined Variables
  2. 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.

Example:

2. BASH_VERSION specifies the shell version which the Bash holds.

Example:

3. COLUMNS specify the no. of columns for our screen.

Example:

4. HOME specifies the home directory for the user.

Example:

5. LOGNAME specifies the logging user name.

Example:

6. OSTYPE tells the type of OS.

Example:

7. PWD represents the current working directory.

Example:

8. USERNAME specifies the name of currently logged in user.

Example:

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.

Output:

Bash Variables

2. Typing the env command

Output:

Bash Variables

3. Typing the printenv command

Output:

Bash Variables

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:

Bash Variables

Step 3. Save and execute the script. It will show the output as you can see in the figure given below.

Output:

Bash Variables

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.

Bash Variables

Step 3. Save and execute the Script.

Output:

Bash Variables

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

Bash Variables

2. Working on Bash Shell

See the script named by Bash_Var given below:

Bash Variables

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:

Output:

Bash Variables

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

Bash Variables

2. Reading and referencing the variables

Bash Variables

3. Invalid Variables

Bash Variables

4. Combining two string variables

Bash Variables

5. Concatenating Strings with variables

Bash 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:

Bash Variables

B. Using Bash Script:

It is an example of combining the String variables.

Bash Variables

Output:

Bash 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.
  • $@ 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:

Bash Variables

Output:

Bash Variables

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 $@ 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:

Program:

On Bash Console:

Bash Variables

Output:

Bash Variables

Command Substitution

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:

Syntax

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.

Bash Variables

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.

Program:

See the Bash Console:

Bash Variables

Output:

Bash Variables
Next TopicRead User Input




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA