Site icon FahmidasClassroom

Use of bash variables

Bp2

Bash variables are a fundamental aspect of shell programming. They are used to store data and information for later use in scripts and commands. Variables can be assigned values by using the equal sign (=) operator. Once a variable has been assigned a value, it can be accessed and used in subsequent commands or scripts. It is important to note that variable names in Bash are case-sensitive, and conventionally, variable names are written in all uppercase letters. It is also good practice to surround variable names with curly braces ({}) when using them in commands or scripts to avoid any confusion with adjacent text.

There are several types of variables in Bash, including system variables, environment variables, and user-defined variables. System variables are predefined by the Bash shell and are used to hold information about the system and the environment in which the shell is running. Environment variables are also predefined by the system, but they can be modified by the user. User-defined variables, on the other hand, are created by the user to store custom data values that are specific to a particular script or command. The uses of these variables are mentioned here.

Bash System variables

System variables in Bash are special variables that are predefined by the operating system and are used to store important information about the system. They are used by the system and the shell to provide useful information to different programs and scripts. One of the most commonly used system variables in Bash is the PATH variable. This variable stores the directories that are searched for executable files when a command is entered. For example, if you type “ls” in the terminal, the system will look for the “ls” executable file in the directories specified in the PATH variable. Another important Bash system variable is the SHELL variable. This variable stores the path to the default shell for the user. This is important as different shells have different features and syntax, and knowing which shell is being used can help avoid errors in scripts. One system variable that is commonly used in scripts is the HOME variable. This variable stores the path to the user’s home directory, which is where all the user’s personal files and settings are stored. Scripts can use this variable to access files and directories within the user’s home directory.

Bash Environment variables

In Bash, environment variables are variables that are set within the shell’s environment and can be accessed by any child process of the shell. These variables contain information that can be used by programs, scripts, and other processes running on the system. Some examples of commonly used environment variables are mentioned here.

USER: Specifies the current user’s username

PS1: Specifies the shell prompt format

PWD: Specifies the current working directory

To set an environment variable in Bash, you can use the “export” command followed by the variable name and value. For example, `export MY_VAR=”Hello, world!”` command will set the environment variable “MY_VAR” to the value “Hello, world!”. You can then access this variable in other scripts or processes with: echo $MY_VAR. The output will be “Hello, world!”. Environment variables are useful for a variety of purposes, such as configuring the behavior of programs, setting default values for parameters, and specifying system-wide settings. They are often used in configuration files and scripts, and can be customized by users to suit their needs. In addition to the commonly used environment variables mentioned above, there are many other variables that can be set in Bash.

Bash Shell variables

The variables which are declared by the user for Bash Shell programming are called Bash shell variables or user-defined variables. No ‘$’ symbol is used at the time of declaring the shell variable but when the value of the variable is required to access then you have to use ‘$’ symbol in the front of the variable name. You can store simple text strings, numerical values, arrays, and even command output into the Bash shell variables. Shell variables can also be exported, allowing them to be accessed by other scripts or processes. Bash is a weakly typed programming language. So, no datatype is required to declare an user-defined variable. But the `declare` command can be used to declare a variable with type in bash. The ways of declaring shell variables without and with `declare` command has been shown here.

Variable declaration without type

Create a bash file with the following script that will define four types of variables to number, string, array, and command output.

#!/bin/bash 
#Store number data 
var1=10 
#Store string data 
var2="Bash Programming Guide" 
#Store array data 
var3=("Bash", "Python", "Perl") 
#Store command output 
var4=`date`

Variable declaration with type

The `declare` command contains many options to set the attribute of the shell variables which are mentioned below.

Option Purpose

-i

The type of the variable will be integer.
-a The type of the variable will be a numeric array.
-A The type of the variable will be an associative array.
-l The value of the variable will be all lowercase letters.
-u The value of the variable will be all uppercase letters.
-r The variable will be read-only.
-n The variable can be used as the name reference of another variable.
-t The variable can be used with the function.
-x The variable can be exported to the child process.

Create a bash file with the following script that will declare four types of variables by using `declare` command.

#!/bin/bash 
#Define integer variable 
declare -i num 
#Define numeric variable 
declare -a numarr1 
#Define associative variable 
declare -A numarr2 
#Define read-only variable 
declare -r str="Bash" 
#Try to re-assign into a read-only variable 
str="Bash"

The output shows that the read-only variable can’t be re-assigned.

Print output

The `echo` and `printf` commands are used in Bash to print the output in the terminal. The uses of these commands are mentioned below.

Print using `echo` command

The Bash `echo` command is a built-in function of the Bash shell that outputs text to the terminal. It is commonly used to display messages, print variables, and create shell scripts. It contains many options to print data in different ways in bash. The syntax and options of `echo` are mentioned here.

Syntax:

echo [option] [string]

When the `echo` command is used without any argument then a newline will be generated.

Options:

Most commonly used options of the `echo` command are mentioned here.

OptionPurpose
-nIt prints the output without the newline.
-e It prints the output by enabling the escape characters.
-E It prints the output by disabling the escape characters.

Create a bash file with the following script that show the uses of `echo` command.

#!/bin/bash 
#Define a variable 
var=100 
#Print a newline 
echo 
#Print string with variable 
echo "The value of the variable $var" 
#Print string without newline 
echo -n "Use of bash 'echo' to print" 
#Print string with escape characters 
echo -e "nBashtPython" 
#Print string without escape character 
echo -E "BashtProgramming"

The following output will appear after executing the script.

Print using `printf` command

The bash `printf` command is a powerful tool for formatting and printing output in the Linux command line. It allows users to customize the way text is displayed by using special formatting codes and arguments. One of the main advantages of using the `printf` command is its ability to print text and variables in a single command, rather than using multiple `echo` commands.

Syntax:

printf [-v var] [specifiers] [variable or value]

Here, the optional argument -v is used to store the output into a variable. The second optional argument specifier is used to format the output. The last optional argument can be a string or variable.

Specifiers:

Most commonly used specifiers of the `printf` command have been mentioned here.

Specifier

Purpose

%s Print the string value.
%d Print the decimal value.
%c Print the character value.
%i Print the integer value.
%f Print the float value.
%o Print the octal value.

%x

Print the hexadecimal value.
%% Print the percentage sign (%).

n

Print a newline.

t

Print the tab space.

Create a bash file with the following script that shows the uses of `printf` command.

#!bin/bash 
#Define a string variable 
book="Bash Programming" 
#Define float number 
price=34.99 
#Define single character 
currency='$' 
#Print output using `printf`command 
printf "Book name: %sn" "$book" 
printf "Book price: %c%0.2fn" "$currency" "$price"

The following output will appear after executing the script.

Bash User Input

The input can be taken in different ways in bash. The `read` command is used in bash to take input from the user. The `read` command can be used with zero or more variables as argument(s). Different uses of the `read` command have been shown here.

Syntax of `read` command

read [variable1 [variable2] … [variableN]]

`read` command without variable

Create a bash file with the following script where the `read` command has been used without any argument. The $REPLY variable is used to store the input value taken by the `read` command without any variable.

#!/bin/bash 
#Print prompt message for the user 
echo -n "Enter your favorite color: " 
#Take input in the default built-in variable 
read 
#Print message with the input value 
echo "Your favorite color is $REPLY"

The following output will appear after executing the script for the input value, ‘Blue’.

`read` command with a variable

Create a bash file with the following script where the `read` command has been used with a variable as an argument.

#!/bin/bash 
#Print prompt message to take a number 
echo -n "Enter the first number: " 
#Take input into number1 variable 
read number1 
#Print prompt message to take another number 
echo -n "Enter the second number: " 
#Take input into number2 variable 
read number2 
((sum=number1+number2)) 
#Print the sum of two input values 
echo "The sum of $number1 and $number2 is $sum"

The following output will appear after executing the script for the input values, 55 and 45.

`read` command with multiple variables

Create a bash file with the following script where the `read` command has been used with three variables as arguments.

#!/bin/bash 
#Print prompt message for the user 
echo -n "Enter your favorite hobbies: " 
#Take input in three variables 
read var1 var2 var3 
#Print message with three input values 
echo "Your like $var1, $var2, and $var3"

The following output will appear after executing the script for the input values, reading, singing, and traveling.

`read` command with different options

Create a bash file with the following script where the uses of three options of the `read` command have been shown. The -p option is used to print the prompt message while taking input from the user. The -s option of the `read` command is used to take secret input that will not be shown in the terminal. The -n option of the `read` command is used to set the character limit of the input.

#!/bin/bash
#Take input from the user with prompt message 
read -p "Enter the email address: " email 
#Take input from the user secretly and the length can be 10 
read -p "Enter the password: " -s -n 10 password 

#Check the input values 
if [[ $email == "admin@example.com" && $password == "topsecret" ]]; then 
echo "Email and password are correct." 
else 
echo "Email and password are incorrect." 
fi

The following output will appear after executing the script for the input values, ‘admin@example.com’ and ‘topsecret’.

Bash command-line argument

The command-line arguments are used to take data at the time of executing the script. The command-line argument can be taken in two ways in bash. One way is to use the argument variables, $1, $2, $3, etc. Another way is to use the getopts function.

Read command-line argument by argument variables

Create a bash file with the following script where three command-line arguments will be read by $1, $2, $3 variables.

#!/bin/bash 
#Read the first argument 
code=$1 
#Read the second argument 
name=$2 
#Read the third argument 
credit=$3 

#Print the argument values 
printf "Course code: %sn" $code 
printf "Course code: %sn" "$name" 
printf "Credit hour: %0.1fn" $credit

The following output will appear after executing the script for the command-line argument values, CSE-307, “Data Structure”, and 2.0.

Read command-line argument by getopts

Create a bash file with the following script where three command-line arguments with three options have been shown.

#!/bin/bash 
#Read command-line argument with options 
while getopts ":c:n:r:" argval; do 
case $argval in 
c) code=$OPTARG;; 
n) name=$OPTARG;; 
r) credit=$OPTARG;; 
esac 
done 
#Print the argument values 
printf "Course code: %sn" $code 
printf "Course name: %sn" "$name" 
printf "Credit hour: %0.1fn" $credit

The following output will appear after executing the script with three options and the command-line argument values.

Bash variables

Exercises

  1. Write a bash script to take three values from the user where the first value will be taken with the -p option of the `read` command and the second value will be taken with the -n option of the `read` command.
  2. Write a bash script that will take five numbers as command-line arguments. Find out the sum of the 1st, 3rd, and 5th arguments.

Summary

The concept of using different bash variables, taking input from the users and the uses of the bash command-line arguments have been explained in this chapter.

Exit mobile version