SHELL SCRIPT
A shell is an environment in which we can run our commands, programs, and shell scripts.
Through shell we can interact with the UNIX system. It gathers input from you and executes programs
based on that input. When a program finishes executing, it displays the program's output.
A shell script is a simple way to write and run multiple commands in one file instead of typing them one by
one in the terminal.
Once the file is executed, all the commands in the file will be executed one by one automatically.
It is used for automating tasks instead of running commands one by one.
A shell script is a file that contains UNIX commands.
SHELL TYPES :
In UNIX there are two major types of shells :
The Bourne shell : If you are using a Bourne-type shell, the default prompt is the $character.
The C shell : If you are using a C-type shell, the default prompt is the % character.
OPEN THE TERMINAL AND TYPE :
vi [Link] [ jeeva => filename & .sh => indicates shell script extension for easy identification ]
It will open the file as normal file. Go to insert mode and start adding the content to the file.
Once added, save and exit the file.
If we run the file, it will throw permission denied error.
To fix the issue, we need to change the permission of the file. Only for the owner have provided all access
and for the rest no access given. Once the permission is changed, then run the file.
chmod 700 file_name
To run the sh file, we need to execute like below.
. => refers current directory.
[Link] => shell file
Or we can run the script file using below
It will display the output in the terminal itself.
HOW TO GET CURRENT DATE AND TIME IN SHELL :
Type date in the shell it will list out the details about the current day, date, time.
VARIABLES :
Variables are used to hold values. It could be number, text, filename, device, or any other type of data.
A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete
variables. No space to be given before and after =.
A = jeeva (Incorrect), A=jeeva(Correct)
Variable names :
Variable name can contain only letters( a to z or A to Z), numbers( 0 to 9) or the underscore character ( _ ).
By convention, Unix Shell variables would have their names in UPPERCASE. The reason you cannot use other
characters such as !,*, or - is that these characters have a special meaning for the shell.
Valid Name Convention Invalid Name Convention
_JEEVA 2_VAR
TOKEN_A -VARIABLE
VAR_1 VAR1-VAR2
VAR_2 VAR_A!
Scalar variables :
This kind of variables can be used to store only one value at the time.
a=jeeva
a=selvaraj
If we want to print the variable value we need to use $ before the variable name like $a. If we print the $a, it
will print “selvaraj” as “jeeva” got overwritten by this value.
Actual file content After executing the file
READ ONLY VARIABLES :
If we don’t want the variables to be changed after declaration, then we can use readonly keyword.
READONLY – to be in lowercase but I’ve tried uppercase and it shows command not found.
Used the readonly keyword and try to execute the file, it will show readonly variable message since in the file
we tried to overwrite the variable with another value.
HOW TO UNSET A VARIABLE :
We can unset a variable by using unset keyword. Using this, variable will be ignored while execution. It won’t
work if a readonly keyword is present before the unset keyword.
Here, on the second line I mentioned readonly and then I mentioned unset so when executing the file, it will
show the output can’t unset due to readonly applied before for the variable a.
VARIABLE TYPES :
Local Variable :
A variable that is only accessible within a specific function or script. Once the function ends, the local variable
is destroyed and can’t be accessed outside of it.
Environmental Variable :
Environmental variables can be accessed anywhere in the program.
User-defined Variables :
These variables are created by the user.
System Variables :
These variables are predefined by the shell.
On the terminal enter $USER, $HOME it will display the owner information
How to read input into a variable :
We can use read keyword followed by a variable name. So, when we run the file we can enter the input
If we don’t know the how many arguments to be passed, then we can use $*, $@
How to check the status of the program executed successfully or not ?
If the program runs successfully, then using $? will return 0 indicates successful and if returns 1 then it is not
successful.
Array :
An array variable can hold multiple values as well as can hold multiple datatypes. Here I’ve declared a variable
name with the index number to assign a values. We can access values using index number.
File content Output
Accessing multiple values of an array using *:
File content Output
Accessing multiple values of an array using @:
File content Output
OPERATORS :
Operators are used to perform specific operations. There are various operators supported by each shell.
Arithmetic Operators
Relational Operators
Boolean Operators
String Operators
File Test Operators
There are following points to note down:
There must be spaces between operators and expressions for example 2+2 is not correct, whereas it
should be written as 2 + 2.
Complete expression should be enclosed between ``, called inverted commas.
ARITHMETIC OPERATORS :
Used to perform basic mathematics operations. Like Addition, subtraction, multiplication, division and so on..
You should use \ on the * symbol for multiplication. Else it will throw an error.
File Content Output
RELATIONAL OPERATORS :
It can be applied for the numeric values. These operators would not work for string values unless their value is
numeric.
We have greater than, less than, equal to, not equal to, greater than or equal to, less than or equal to.
It is very important to note here that all the conditional expressions would be put inside square braces with one
spaces around them, for example [ $a <= $b ] is correct where as [$a <= $b] is incorrect.
Boolean Operators :
It is used to check and combine multiple conditions.
! – Logical Not – It reverse the result e.g. True to False and False to True
-o – Logical Or - If one of the operands condition is true, then overall result would be true.
-a – Logical And - If both operands are true, then condition would be true otherwise it would be false.
STRING OPERATORS :
It is used to compare strings with the help of the operators.
Operato Description SS
r
= Checks if the value of two operands is equal or not, if
yes then condition becomes true.
= Checks if the value of two operands is equal or not, if
values are not equal then condition becomes true
-z Checks if the given string operand size is zero. If it is
zero length then it returns true.
-n Checks if the given string operand size is non-zero. If it
is non-zero length, then it returns true.
-Str Checks if the given string operand size is non-zero. If it
is non-zero length, then it returns true.
File Test Operators :
We can use this operator to check the permission of the file as well as other information.
File Content :
Output :
DECISION MAKING STATEMENTS :
When we need to execute certain blocks based on the condition, then we can use decision statement so that
based on the condition it will get executed.
We can use below two conditional statements :
if……else
case…..esac
Simple if……fi :
if......fi is used to check only for one condition and only if condition is true then it will execute its blocks of
content. If the condition is false, it will not display anything.
Syntax :
if [ expression ]
then
Statement(s) to be executed if expression is true
Fi
Example :
if….else….fi :
When if condition gets false, then we can use else block as it will execute those statements.
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true fi
Example :
if...elif...else...fi statement :
When we need to check more than 1 condition we can use this control statement.
Syntax :
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
Fi
Example :
Find odd or even using if :
File Content Output
case…….esac :
We can also use case……esac as well for the control statements. You can use multiple if...elif statements to
perform a multiway branch. However, this is not always the best solution, especially when all the branches
depend on the value of a single variable. Shell support case...esac statement which handles exactly this
situation, and it does so more efficiently than repeated if...elif statements.
Syntax :
case word in
pattern1) Statement(s) to be executed if pattern1 matches ;;
pattern2) Statement(s) to be executed if pattern2 matches ;;
pattern3) Statement(s) to be executed if pattern3 matches ;;
*) Statement(s) to be executed if pattern matches ;;
esac
Example :
Find odd or even using case :
File Content Output
Loop Control :
When we want to perform repetitive task, we can use loop statement. There are 2 types.
For loop
While Loop
For loop Syntax :
The for loop operate on lists of items. It repeats a set of commands for every item in a list.
Syntax :
for var in word1 word2 ...... wordN
do
Statement(s) to be executed for every word.
Done
Example :
File Content Output
File Content Output
Iterate through range :
We can also use {1..2} to list out the numbers as per the range given.
File Content Output
Iterate through all items from an array :
We can iterate through a list of arrays using elements using for loop.
File Content Output
How to remove element from the array :
File Content Output
While loop :
The loop will continue to execute till the condition gets true. Once the condition gets false it will exit the loop.
Syntax :
while command
do
Statement(s) to be executed if command is true
Done.
File Content Output