Debug School

rakesh kumar
rakesh kumar

Posted on

Bash Variables and Read User Input

What are Bash Variables?
Rules Set for Defining Bash Variables:
Data Types
Types of Bash Variables
Working of Bash Variables
Command line Arguments
Command Substitution

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:

Variable_name =value  
Enter fullscreen mode Exit fullscreen mode

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:
Variable_name=value

Rules Set for Defining Bash Variables:

Image description

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:

int year=2012  
char comp_name='jtp' 
Enter fullscreen mode Exit fullscreen mode

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.

year=2012  
comp_name=jtp 
Enter fullscreen mode Exit fullscreen mode

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.

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.

Example:

BASH=/usr/bin/bash  
Enter fullscreen mode Exit fullscreen mode
  1. BASH_VERSION specifies the shell version which the Bash holds.

Example:

BASH_VERSION=4.2.46(2)  
Enter fullscreen mode Exit fullscreen mode
  1. COLUMNS specify the no. of columns for our screen.

Example:

COLUMNS=80  
Enter fullscreen mode Exit fullscreen mode
  1. HOME specifies the home directory for the user.

Example:

HOME=/home/jatpoint  
Enter fullscreen mode Exit fullscreen mode
  1. LOGNAME specifies the logging user name.

Example:

LOGNAME=javatpoint  
Enter fullscreen mode Exit fullscreen mode
  1. OSTYPE tells the type of OS.

Example:

OSTYPE=linux-gnu  
Enter fullscreen mode Exit fullscreen mode
  1. PWD represents the current working directory.

Example:

PWD=/home/javatpoint  
Enter fullscreen mode Exit fullscreen mode
  1. USERNAME specifies the name of currently logged in user.

Example:

USERNAME=javatpoint  
Enter fullscreen mode Exit fullscreen mode

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:

Image description

  1. Typing the env command

Output:

Image description

  1. Typing the printenv command

Output:

Image description

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:

#! /bin/bash  
# Bash System-defined Variables  
echo $HOME # Home Directory  
echo $PWD # current working directory  
echo $BASH # Bash shell name  
echo $BASH_VERSION # Bash shell Version  
echo $LOGNAME # Name of the Login User  
echo $OSTYPE # Type of OS 
Enter fullscreen mode Exit fullscreen mode

Step 2. Look at the Bash Console given below:

Image description

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

Output:

Image description

  1. 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:

#! /bin/bash  
# User-Defined Variables   
name=Peter  
ROLL_NO=5245325  
echo "The student name is $name and his Roll number is $ROLL_NO." 
Enter fullscreen mode Exit fullscreen mode

Step 2. See the code on Bash Console.

Image description

Step 3. Save and execute the Script.

Output:

Image description

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

Image description

  1. Working on Bash Shell See the script named by Bash_Var given below:

Image description

Image description

For better understanding, create this script by following the given code:

#! /bin/bash  
#Bash Variables  
USER_NAME=XYZ  
echo Hey there! $USER_NAME is any user currently working on the 
Enter fullscreen mode Exit fullscreen mode

directory $PWD with Bash Shell Version $BASH_VERSION.

It will show the output as you can see in the following image:

Output:

Image description

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

Image description

Reading and referencing the variables

Image description

Invalid Variables

Image description

combining two string variables

Image description

Concatenating Strings with variables

Image description

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:

Image description

Using Bash Script:

It is an example of combining the String variables.

Image description

Output:

Image description

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:

./script_name arg1 arg2 arg3.....  
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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:

Image description

Output:

Image description

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:

variable_name=("$@")

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:

${variable_name[i]}

Step 4: Save and close the Script.

Step 5: Execute the Script by passing the arguments.

See the following program:

Program:

#!/bin/bash  

args=("$@")  

echo ${args[0]} ${args[1]} ${args[2]} ${args[3]}  
Enter fullscreen mode Exit fullscreen mode

On Bash Console:

Image description

Output:

Image description

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:

variable_name=`command_name`  
variable_name=`command_name [option...] argument1 argument2...`  
variable_name=`/path/to/command` 
Enter fullscreen mode Exit fullscreen mode

Now, we do command substitution by enclosing the commands within brackets (preceded by the dollar sign ($)). Have a look:

variable_name=$(command_name)  
variable_name=$(command_name [option...] argument1 argument2...)  
variable_name=$(path/to/command) 
Enter fullscreen mode Exit fullscreen mode

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.

Image description

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:

#! /bin/bash  

# command substitution  

lsResult=$(ls)  
echo "My files are:" $lsResult 
Enter fullscreen mode Exit fullscreen mode

See the Bash Console:

Image description

Output:

Image description

Read User Input

In this topic, we will learn how to read the user input from the terminal and the script.

To read the Bash user input, we use the built-in Bash command called read. It takes input from the user and assigns it to the variable. It reads only a single line from the Bash shell. Below is the syntax for its implementation.

Syntax

read <variable_name>  
Enter fullscreen mode Exit fullscreen mode

Follow the given examples to read user input from the Bash Script:

Example 1:
In this example, we read both the single and multiple variables from the Bash Script by using read command.

Program:

!/bin/bash

Read the user input

echo "Enter the user name: "  
read first_name  
echo "The Current User Name is $first_name"  
echo  
echo "Enter other users'names: "  
read name1 name2 name3  
echo "$name1, $name2, $name3 are the other users." 
Enter fullscreen mode Exit fullscreen mode

See the Bash Console:

Image description

Output:

Image description

What will happen if we don't pass any variable with the read command?
If we don't pass any variable with the read command, then we can pass a built-in variable called REPLY (should be prefixed with the $ sign) while displaying the input. It can be explained using the below program:

Program:
#!/bin/bash  

# using read command without any variable  

echo "Enter name : "  

read  

echo "Name : $REPLY" 
Enter fullscreen mode Exit fullscreen mode

On Bash Console:

Image description

Output:

Image description

Example 2:
In this example, we enter the input on the same PROMPT by using the -p command line option as follows:

read -p PROMPT <variable_name>  
Enter fullscreen mode Exit fullscreen mode
Program:
#!/bin/bash  

read -p "username:" user_var  
echo "The username is: " $user_var  
Enter fullscreen mode Exit fullscreen mode

See the Bash Console:

Image description

Example 3:
This example is to keep the input on silent mode, such that whatever be a user input on the command line will be hidden to others.

So, we pass a username and hide the password (silent mode) by using the command line options (-s, -p) commonly as follows:

read -sp PROMPT <variable_name>  
Enter fullscreen mode Exit fullscreen mode

Where -s allows a user to keep the input on silent mode and -p to input on newly command prompt.

Program:

!/bin/bash

read -p "username : " user_var  
read -sp "password : " pass_var  
echo  
echo "username : " $user_var  
echo "password : "  $pass_var  
Enter fullscreen mode Exit fullscreen mode

See the Bash Console:

Image description

Image description

Image description

So, write your script by adding a blank echo command line.

Example 4: This example is to enter multiple inputs using an array. So use the -a command line option as follows:

read -a <variable_name>  
Enter fullscreen mode Exit fullscreen mode

Where -a helps script to read an array, and variable_name refers to an array.

Program:
#!/bin/bash  

# Reading multiple inputs using an array  

echo "Enter names : "  
read -a names  
echo "The entered names are : ${names[0]}, ${names[1]}."  
Enter fullscreen mode Exit fullscreen mode

See the code on Bash Console:

Image description

Top comments (0)