0% found this document useful (0 votes)
2 views52 pages

Unix Shell Script Bca 4th Sem 2nd Module

The document provides an overview of variables in shell scripting, categorizing them into local, global, and shell variables, and explains their scope and usage. It also covers the read and export commands in Linux, detailing their syntax and options, as well as basic operators in shell scripting including arithmetic, relational, logical, bitwise, and file test operators. Examples are provided for each concept to illustrate their application in shell scripts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views52 pages

Unix Shell Script Bca 4th Sem 2nd Module

The document provides an overview of variables in shell scripting, categorizing them into local, global, and shell variables, and explains their scope and usage. It also covers the read and export commands in Linux, detailing their syntax and options, as well as basic operators in shell scripting including arithmetic, relational, logical, bitwise, and file test operators. Examples are provided for each concept to illustrate their application in shell scripts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SRI AKSHAYA DEGREE COLLEGE HOSPET

Variables in Shell Scripts: System Variables vs. User-defined


Variables
The shell is a command-line interpreter for Linux and Unix systems. It provides an
interface between the user and the kernel and executes commands. A sequence of
commands can be written in a file for execution in the shell. It is called shell
scripting. It helps to automate tasks in Linux.
Scripting language also has concepts of different types of variables like procedural
or object-oriented languages.
In shell scripting there are three main types of variables are present. They are -
Local Variables
 Global Variables or Environment Variables
 Shell Variables or System Variables
We will discuss them one by one in this article -

Local Variable
A local variable is a special type of variable which has its scope only within a
specific function or block of code. Local variables can override the same variable
name in the larger scope. Let's understand this concept using an example -
Shell script:
#!/bin/sh

getName(){
NAME=SATYAJIT #local variable
echo "$NAME (from function)" #valid if called using function
}

echo "$NAME - (outside function)" #invalid here


getName
Output:
- (outside function)
SATYAJIT (from function)
In this example, NAME is a local variable and its scope is limited within the
getName() function. So, when we try to call it from outside the function, there is

pg. 1 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

nothing in output. Next, when we call the function then it's displayed on the output
screen. Below is the terminal shell pictorial depiction after executing the following
shell script :-

Global Variables
A global variable is a variable with global scope. It is accessible throughout the
program. Global variables are declared outside any block of code or function. Let's
understand this concept using an example -
Shell script:
#!/bin/sh

NAME=SATYAJIT #global variable

getName(){
echo "$NAME (from function)"
}

echo "$NAME - (outside function)"


getName

pg. 2 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Output:
SATYAJIT - (outside function)
SATYAJIT (from function)
Now, we have updated the earlier example code and declared the variable
NAME outside any function. It makes the NAME variable a global variable that has
its scope all over the program. Thus, it can be accessed from inside or outside a
function. Below is the terminal shell pictorial depiction after executing the following
shell script:-

Though, if we execute another shell script from a shell script, then local and global
variables will be ignored by the new shell. Thus, if we want to make variables truly
global, then we have to use the export command. Let's understand this concept using
an example -
Shell script:
gfg_1.sh
#!/bin/sh
NUM=9
echo "gfg_1 : The value is $NUM"
export NUM
./gfg_2.sh
gfg_2.sh

pg. 3 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

#!/bin/sh
echo "gfg_2 : The value is $NUM"
Output
gfg_1 : The value is 9
gfg_2 : The value is 9
Here, the NUM variable is accessible even from the other shell script (gfg_2.sh).
This is because we have used the export command in gfg_1.sh . If we don't use the
export command, then the NUM variable value will not be visible from gfg_2.sh.
Below is the terminal shell pictorial depiction after executing the following shell
script -

Shell Variables
These are special types of variables. They are created and maintained by Linux Shell
itself. These variables are required by the shell to function properly They are
defined in Capital letters and to see all of them, we can use set / env / printenv
command. Below is the terminal shell pictorial depiction after executing the
following command:-

pg. 4 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Some useful shell variables are -

Variable Name Description Usage

Holds the version of this instance of echo


BASH_VERSION
bash. $BASH_VERSION

Provides a home directory of the


HOME echo $HOME
current user.

HOSTNAME Provides computer name echo $HOSTNAME

USERNAME Provides username echo $USERNAME

Below is the terminal shell pictorial depiction after executing the following
commands-

pg. 5 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

read command in Linux with Examples


read command in the Linux system is used to read from a file descriptor. This
command reads up the total number of bytes from the specified file descriptor into the
buffer. If the number or count is zero, this command may detect errors. But on success,
it returns the number of bytes read. Zero indicates the end of the file. If some errors
are found then it returns -1.
Let’s look deeper into its usage, syntax, options, and some common examples.

Syntax
read
The read command takes the user's input and stores it into a variable that can be
referenced later in the script.
Basic read Command Example

pg. 6 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Options for the read Command


Options Description

-p Displays a prompt before reading input.

-t Sets a timeout to wait for input.

pg. 7 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Options Description

-n Limits the number of characters to read.

-s Disables echoing the input (useful for password entry).

-d Defines a delimiter other than a newline.

read Command Examples in Linux


read command without any option: The read command asks for the user's input
and exit once the user provides some input.

In the following example we are acquiring the user's name and then showing the
user's name with a greeting.
echo "what is your name..?";read name;echo "hello $name"

export command in Linux with Examples


The 'export' command is one of the essential built-in commands in the Bash shell,
allowing users to manage environment variables effectively. It is defined in POSIX
standards, which state that the shell will assign the export attribute to specified
variables, causing them to be included in the environment of subsequently executed
commands. Simply put, the export command makes environment variables available
to child processes, enabling changes to be reflected immediately in the current shell
session without needing to start a new session.
What is the 'export' Command?
In Bash, environment variables are set when you start a new shell session, and changes
to these variables are not automatically picked up by the shell. The export command
allows you to update and propagate the values of environment variables to the current
session and any spawned child processes, ensuring that changes are immediately
effective. This feature is crucial for tasks such as setting up paths, configuring
environment-specific variables, or defining settings that multiple programs need to
access.

Syntax:
export [-f] [-n] [name[=value] ...] or export -p
Options of 'export' command
pg. 8 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND
MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

1. Without any argument:


To view all the exported variables.
Example:

2. -p Option:
To view all exported variables on current shell.
Syntax:
$ export -p
Example:

pg. 9 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

3. -f Option:
It must be used if the names refer to functions. If -f is not used, the export will
assume the names are variables.
Syntax:
$ export -f function_name
Example:
To export shell function:

Note: Bash command is used for showing that in the child shell, the shell function
got exported.

pg. 10 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

4. name[=value]:
You can assign value before exporting using the following syntax.
Syntax:
$ export name[=value]
Example:
To set vim as a text editor

Note: No output will be seen on screen, to see exported variable grep from exported
ones is used.
5. -n Option:
Named variables (or functions, with -f) will no longer be exported.
Syntax:
$ export -n variable_name
Example:

Note: No output will be seen on screen, to see exported variable grep from exported
ones is used.

Basic Operators in Shell Scripting


There are 5 basic operators in bash/shell scripting:
 Arithmetic Operators
 Relational Operators
 Boolean Operators
 Bitwise Operators
 File Test Operators
1. Arithmetic Operators: These operators are used to perform normal
arithmetics/mathematical operations. There are 7 arithmetic operators:
 Addition (+): Binary operation used to add two operands.
 Subtraction (-): Binary operation used to subtract two operands.
 Multiplication (*): Binary operation used to multiply two operands.
 Division (/): Binary operation used to divide two operands.
 Modulus (%): Binary operation used to find remainder of two operands.

pg. 11 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

 Increment Operator (++): Unary operator used to increase the value of


operand by one.
 Decrement Operator (- -): Unary operator used to decrease the value of a
operand by one
#!/bin/bash

# reading data from the user


read -r -p "Enter a: " a

read -r -p "Enter b: " b

add=$((a+b))
echo "Addition of a and b are: "${add}

sub=$((a-b))
echo "Subtraction of a and b are: "${sub}

mul=$((a*b))
echo "Multiplication of a and b are: "${mul}

div=$((a/b))
echo "Division of a and b are: "${div}

mod=$((a%b))
echo "Modulis of a and b are: "${mod}

((++a))
echo "Increment operator when applied on $a results into a :" "${a}"

((--b))
echo "Decrement operator when applied on 'b' results into b :" "${b}"
Output:

pg. 12 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

2. Relational Operators: Relational operators are those operators which define the
relation between two operands. They give either true or false depending upon the
relation. They are of 6 types:
 '==' Operator: Double equal to operator compares the two operands. Its
returns true is they are equal otherwise returns false.
 '!=' Operator: Not Equal to operator return true if the two operands are
not equal otherwise it returns false.
 '<' Operator: Less than operator returns true if first operand is less than
second operand otherwise returns false.
 '<=' Operator: Less than or equal to operator returns true if first operand
is less than or equal to second operand otherwise returns false
 '>' Operator: Greater than operator return true if the first operand is
greater than the second operand otherwise return false.
 '>=' Operator: Greater than or equal to operator returns true if first
operand is greater than or equal to second operand otherwise returns false
#!/bin/bash

#reading data from the user


read -p 'Enter a : ' a
read -p 'Enter b : ' b

if(( $a==$b ))
then
echo a is equal to b.
else
echo a is not equal to b.
fi

pg. 13 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

if(( $a!=$b ))
then
echo a is not equal to b.
else
echo a is equal to b.
fi

if(( $a<$b ))
then
echo a is less than b.
else
echo a is not less than b.
fi

if(( $a<=$b ))
then
echo a is less than or equal to b.
else
echo a is not less than or equal to b.
fi

if(( $a>$b ))
then
echo a is greater than b.
else
echo a is not greater than b.
fi

if(( $a>=$b ))
then
echo a is greater than or equal to b.
else
echo a is not greater than or equal to b.
fi
Output:

pg. 14 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

3. Logical Operators : They are also known as boolean operators. These are used to
perform logical operations. They are of 3 types:
 Logical AND (&&): This is a binary operator, which returns true if both
the operands are true otherwise returns false.
 Logical OR (||): This is a binary operator, which returns true if either of
the operands is true or if both the operands are true. It returns false only if
both operands are false.
 Not Equal to (!): This is a unary operator which returns true if the operand
is false and returns false if the operand is true.
#!/bin/bash

#reading data from the user


read -p 'Enter a : ' a
read -p 'Enter b : ' b

if(($a == "true" & $b == "true" ))


then
echo Both are true.
else
echo Both are not true.
fi

if(($a == "true" || $b == "true" ))


then
echo Atleast one of them is true.
else
echo None of them is true.
fi

if(( ! $a == "true" ))
then

pg. 15 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

echo "a" was initially false.


else
echo "a" was initially true.
fi
Output:

4. Bitwise Operators: A bitwise operator is an operator used to perform bitwise


operations on bit patterns. They are of 6 types:
 Bitwise And (&): Bitwise & operator performs binary AND operation bit
by bit on the operands.
 Bitwise OR (|): Bitwise | operator performs binary OR operation bit by bit
on the operands.
 Bitwise XOR (^): Bitwise ^ operator performs binary XOR operation bit
by bit on the operands.
 Bitwise complement (~): Bitwise ~ operator performs binary NOT
operation bit by bit on the operand.
 Left Shift (<<): This operator shifts the bits of the left operand to left by
number of times specified by right operand.
 Right Shift (>>): This operator shifts the bits of the left operand to right
by number of times specified by right operand.
#!/bin/bash

#reading data from the user


read -p 'Enter a : ' a
read -p 'Enter b : ' b

bitwiseAND=$(( a&b ))
echo Bitwise AND of a and b is $bitwiseAND

bitwiseOR=$(( a|b ))
echo Bitwise OR of a and b is $bitwiseOR

bitwiseXOR=$(( a^b ))
echo Bitwise XOR of a and b is $bitwiseXOR

pg. 16 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

bitiwiseComplement=$(( ~a ))
echo Bitwise Compliment of a is $bitiwiseComplement

leftshift=$(( a<<1 ))
echo Left Shift of a is $leftshift

rightshift=$(( b>>1 ))
echo Right Shift of b is $rightshift
Output:

5. File Test Operator: These operators are used to test a particular property of a
file.
 -b operator: This operator check whether a file is a block special file or
not. It returns true if the file is a block special file otherwise false.
 -c operator: This operator checks whether a file is a character special file
or not. It returns true if it is a character special file otherwise false.
 -d operator: This operator checks if the given directory exists or not. If it
exists then operators returns true otherwise false.
 -e operator: This operator checks whether the given file exists or not. If it
exits this operator returns true otherwise false.
 -r operator: This operator checks whether the given file has read access or
not. If it has read access then it returns true otherwise false.
 -w operator: This operator check whether the given file has write access
or not. If it has write then it returns true otherwise false.
 -x operator: This operator check whether the given file has execute access
or not. If it has execute access then it returns true otherwise false.
 -s operator: This operator checks the size of the given file. If the size of
given file is greater than 0 then it returns true otherwise it is false.
#!/bin/bash

pg. 17 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

#reading data from the user


read -p 'Enter file name : ' FileName

if [ -e $FileName ]
then
echo File Exist
else
echo File doesnot exist
fi

if [ -s $FileName ]
then
echo The given file is not empty.
else
echo The given file is empty.
fi

if [ -r $FileName ]
then
echo The given file has read access.
else
echo The given file does not has read access.
fi

if [ -w $FileName ]
then
echo The given file has write access.
else
echo The given file does not has write access.
fi

if [ -x $FileName ]
then
echo The given file has execute access.
else
echo The given file does not has execute access.
fi
Output:

pg. 18 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Looping Statements | Shell Script


Loops are a fundamental part of programming, and shell scripting is no
exception. They allow you to automate repetitive tasks by running a block of code
multiple times.
You will use loops for all sorts of common tasks:
 for loop: Iterating over a list of items (e.g., files, servers, usernames).
 while loop: Running code as long as a condition is true (e.g., reading a file
line by line).
 until loop: Running code until a condition becomes true (e.g., waiting for
a file to appear).
`while` statement in Shell Script in Linux
The while loop is used when you don't know how many times to loop, but you know
the condition to stay in the loop.

How it works:
It checks the condition. If it's TRUE, it runs the code, then checks again. It repeats
until the condition is FALSE.
#/bin/bash
while <condition>
do
<command 1>
<command 2>
<etc>
done

pg. 19 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

[Statement]: Implementation of `While` Loop in Shell Script.

First, we create a file using a text editor in Linux. In this case, we are using
`vim`editor.
vim [Link]
 You can replace "[Link]" with the desired name.
 Then we make our script executable using the `chmod` command in Linux.
chmod +x [Link]
#/bin/bash
a=0
# lt is less than operator
#Iterate the loop until a less than 10
while [ $a -lt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done
Output:

While Loop in Linux

Explanation:
 #/bin/bash: Specifies that the script should be interpreted using the Bash
shell.

pg. 20 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

 a=0: Initializes a variable a with the value 0.


 while [ $a -lt 10 ]: Initiates a while loop that continues as long as the value
a is less than 10.
 do: Marks the beginning of the loop's body.
 echo $a: Prints the current value of a the console.
 a=expr $a + 1``: Increments the value of a by 1. The expr command is
used for arithmetic expressions.
 done: Marks the end of the loop
`for` statement in Shell Script in Linux
The for loop operates on lists of items. It repeats a set of commands for every item
in a list.
Syntax:
#/bin/bash
for <var> in <value1 value2 ... valuen>
do
<command 1>
<command 2>
<etc>
done
 Here var is the name of a variable and word1 to wordN are sequences of
characters separated by spaces (words). Each time the for loop executes,
the value of the variable var is set to the next word in the list of words,
word1 to wordN.

[Statement 1]: Implementation of `for` Loop with `break` statement in Shell


Script.

First, we create a file using a text editor in Linux. In this case, we are using
`vim`editor.
vim [Link]
 You can replace "[Link]" with the desired name.
 Then we make our script executable using the `chmod` command in Linux.
chmod +x [Link]
#/bin/bash
#Start of for loop

pg. 21 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

for a in 1 2 3 4 5 6 7 8 9 10
do
# if a is equal to 5 break the loop
if [ $a == 5 ]
then
break
fi
# Print the value
echo "Iteration no $a"
done
Output:

pg. 22 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Explanation:
 #/bin/bash: Specifies that the script should be interpreted using the Bash
shell.
 for a in 1 2 3 4 5 6 7 8 9 10: Initiates a for loop that iterates over the
values 1 through 10, assigning each value to the variable a in each
iteration.
 do: Marks the beginning of the loop's body.
 if [ $a == 5 ]: Checks if the current value a is equal to 5.

pg. 23 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

 echo "Iteration no $a": Prints a message indicating the current iteration


number.
 done: Marks the end of the loop.
The script sets up a for loop that iterates over the values 1 through 10. During each
iteration, it checks if the value a is equal to 5. If it is, the loop is exited using the
break statement. Otherwise, it prints a message indicating the current iteration
number. The loop continues until it completes all iterations or until it encounters a
break statement.

[Statement 2]: Implementation of `for` Loop with `continue` statement in


Shell Script.

First, we create a file using a text editor in Linux. In this case, we are using
`vim`editor.
vim for_continue.sh
 You can replace "for_continue.sh" with the desired name.
 Then we make our script executable using the `chmod` command in Linux.
chmod +x for_continue.sh
#/bin/bash
for a in 1 2 3 4 5 6 7 8 9 10
do
# if a = 5 then continue the loop and
# don't move to line 8
if [ $a == 5 ]
then
continue
fi
echo "Iteration no $a"
done
Output:

pg. 24 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

continue
statement in for loop in Linux

Explanation:
 #/bin/bash: Specifies that the script should be interpreted using the Bash
shell.
 for a in 1 2 3 4 5 6 7 8 9 10: Initiates a for loop that iterates over the
values 1 through 10, assigning each value to the variable a in each
iteration.
 do: Marks the beginning of the loop's body.
 if [ $a == 5 ]: Checks if the current value a is equal to 5.
 echo "Iteration no $a": Prints a message indicating the current iteration
number. This line is skipped if a is equal to 5 due to the continue
statement.
 done: Marks the end of the loop.
The script sets up a for loop that iterates over the values 1 through 10. During each
iteration, it checks if the value a is equal to 5. If it is, the loop continues to the next
iteration without executing the remaining statements in the loop's body. Otherwise,
it prints a message indicating the current iteration number. The loop continues until
it completes all iterations.

`until` statement in Shell Script in Linux


The until loop is executed as many times as the condition/command evaluates to
false. The loop terminates when the condition/command becomes true.
Syntax:
#/bin/bash
until <condition>
do
<command 1>
<command 2>

pg. 25 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

<etc>
done

[Statement]: Implementing `until` Loop in Shell Script

First, we create a file using a text editor in Linux. In this case, we are using
`vim`editor.
vim [Link]
 You can replace "until. sh" with the desired name.
 Then we make our script executable using the `chmod` command in Linux.
chmod +x [Link]
#/bin/bash
a=0
# -gt is greater than operator
#Iterate the loop until a is greater than 10
until [ $a -gt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done
Output:

pg. 26 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Explanation:
 #/bin/bash: Specifies that the script should be interpreted using the Bash
shell.
 a=0: Initializes a variable a with the value 0.
 until [ $a -gt 10 ]: Initiates a until loop that continues as long as the value
a is not greater than 10.
 do: Marks the beginning of the loop's body.
 echo $a: Prints the current value of a the console.
 a=expr $a + 1``: Increments the value of a by 1. The expr command is
used for arithmetic expressions.
 done: Marks the end of the loop.
Note: Shell scripting is a case-sensitive language, which means proper syntax has to
be followed while writing the scripts.
Examples of Looping Statements
Below are some commonly used looping statements along with their basic structure
and examples.

pg. 27 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

[Example 1]: Iterating Over Colors Using a For Loop

First, we create a file using a text editor in Linux. In this case, we are using
`vim`editor.
vim [Link]
 You can replace "[Link]" with the desired name.
 Then we make our script executable using `chmod` command in Linux.
chmod +x [Link]
#/bin/bash
COLORS="red green blue"
# the for loop continues until it reads all the values from the
COLORS
for COLOR in $COLORS
do
echo "COLOR: $COLOR"
done
Output:

For until in Linux

Explanation:
1. Initialization of Colors:
 COLORS="red green blue": Initializes a variable named COLORS with a
space-separated list of color values ("red", "green", and "blue").
2. For Loop Iteration:
 for COLOR in $COLORS: Initiates a for loop that iterates over each value
in the COLORS variable.
3. Loop Body:
 echo "COLOR: $COLOR": Prints a message for each color, displaying the
current color value.
 The loop continues until it processes all the values present in the COLORS
variable.

pg. 28 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

This example demonstrates a simple for loop in Bash, iterating over a list of colors
stored in the COLORS variable. The loop prints a message for each color, indicating
the current color being processed. The loop iterates until all color values are
exhausted.

[Example 2]: Creating an Infinite Loop with "while true" in Shell Script

First we create a file using a text editor in Linux. In this case we are using
`vim`editor.
vim [Link]
 You can replace "[Link]" with desired name.
 Then we make our script executable using `chmod` command in Linux.
chmod +x [Link]
#/bin/bash
while true
do
# Command to be executed
# sleep 1 indicates it sleeps for 1 sec
echo "Hi, I am infinity loop"
sleep 1
done
Output:

infinite loop in linux

Explanation:
Infinite Loop Structure:
1. while true: Initiates a while loop that continues indefinitely as the condition true
is always true.
2. Loop Body:

pg. 29 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

 echo "Hi, I am infinity loop": Prints a message indicating that the script
is in an infinite loop.
 sleep 1: Pauses the execution of the loop for 1 second before the next
iteration.
 The loop continues indefinitely, executing the commands within its body
repeatedly.
This example showcases the creation of an infinite loop using the while true
construct in Bash. The loop continuously prints a message indicating its status as an
infinite loop and includes a sleep 1 command, causing a one-second delay between
iterations. Infinite loops are often used for processes that need to run continuously
until manually interrupted.

[Example 3]: Interactive Name Confirmation Loop

First we create a file using a text editor in Linux. In this case we are using
`vim`editor.
vim [Link]
 You can replace "[Link]" with desired name.
 Then we make our script executable using `chmod` command in Linux.
chmod +x [Link]
#/bin/bash
CORRECT=n
while [ "$CORRECT" == "n" ]
do
# loop discontinues when you enter y i.e., when your name is
correct
# -p stands for prompt asking for the input
read -p "Enter your name:" NAME
read -p "Is ${NAME} correct? " CORRECT
done
Output:

pg. 30 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Conditional Statements | Shell Script


Conditional statements, or if-then blocks, are the most important part of any script.
They are the "decision-makers" that allow your script to run, skip, or change code
based on a specific condition.
You will use conditional logic for all sorts of common tasks:
 Checking if a file or directory exists before trying to read or write to it.
 Validating user input to see if it's a valid number or string.
 Running a command only if a previous command was successful.
 Checking if a user has "root" permissions.
A Simple 'if' Script
This script asks for a number and tells you if it's greater than 10.
Command:
#!/bin/bash

read -p "Enter a number: " NUMBER

# The [ ... ] is a test.


# -gt means "greater than".
if [ "$NUMBER" -gt 10 ]; then
echo "Your number ($NUMBER) is greater than 10."
fi

echo "Script finished."


Output:

pg. 31 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

"if" Checks for Exit Status 0


This is the most important concept to understand: if does not test for "true" or
"false".
 Instead, the if statement runs a command.
 If the command succeeds (returns an exit status of 0), the then block is
executed.
 If the command fails (returns a non-zero exit status), the then block is
skipped.
if grep -q "ERROR" /var/log/syslog; then echo "An error was found
in the log!" # send an email, restart a service, [Link]
Here, the if statement runs the grep -q "ERROR" ... command. If grep finds the
string "ERROR" (success, exit code 0), the then block runs.

How to Build Logic


You can stack if statements to build complex logic.

1. The if

 What it does: Runs code only if the condition is true.


Syntax:
if [ condition ]; then
# code to run...
fi

2. The if...else...fi

 What it does: Provides an alternative block of code to run if the condition


is false.
Syntax:
if [ condition ]; then
# code to run if true...
else
# code to run if false...
fi
Example (File check):
if [ -f "/etc/hosts" ]; then
echo "The /etc/hosts file exists."
else

pg. 32 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

echo "Error: /etc/hosts file not found."


fi

3. The if...elif...else...fi

 What it does: Lets you chain multiple "else if" conditions. This is the
cleanest way to check for multiple, mutually exclusive options.
Syntax:
if [ condition1 ]; then
# code for condition1...
elif [ condition2 ]; then
# code for condition2...
elif [ condition3 ]; then
# code for condition3...
else
# code to run if nothing matches...
fi
Example :
#!/bin/bash

# Get the current hour (00-23)


HOUR=$(date +%H)

if [ "$HOUR" -lt 12 ]; then


echo "Good morning!"
elif [ "$HOUR" -lt 18 ]; then
echo "Good afternoon!"
else
echo "Good evening!"
fi

The if Statement Sheet


You must use the correct operator for what you are testing (files, strings, or
numbers).

pg. 33 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

1. File Test Operators (Use with [[ -f $file ]])

Operator What It Checks

-e $file True if file exists (file or directory).

-f $file True if file is a regular file.

-d $dir True if dir is a directory.

-r $file True if file is readable.

-w $file True if file is writable.

-x $file True if file is executable.

-s $file True if file is not empty (has a size > 0).

2. String Test Operators (Use with [[ "$str1" == "$str2" ]])

Operator What It Checks

[[ "$str1" == "$str2" ]] True if strings are equal. (Note: == is an alias for = in [[...]])

[[ "$str1" != "$str2" ]] True if strings are not equal.

[[ -z "$str" ]] True if string is empty (has zero length).

pg. 34 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Operator What It Checks

[[ -n "$str" ]] True if string is not empty (has non-zero length).

3. Integer Test Operators (Use with [ "$num" -eq 10 ])

Operator What It Checks

-eq Equal

-ne Not Equal

-gt Greater Than

-ge Greater than or Equal

-lt Less Than

-le Less than or Equal

Example:
if [[ "$USER" == "root" && "$num" -gt 10 ]]; then echo "You are
root and the number is greater than 10."fi

Linux Permissions & How to Set File Permissions


Linux file permissions form the foundation of the system’s security model. They
define who can read, write, or execute files and directories, ensuring only authorized
users or processes can access sensitive data. You can modify these permissions
using the chmod command.

pg. 35 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

 chmod +rwx filename – Adds read, write, and execute permissions.


 chmod -rwx directoryname – Removes all permissions.
 chmod +x filename – Grants executable permission.
 chmod -wx filename – Removes write and execute rights.
1. The Three Basic Permissions
Every file or directory has three types of permissions:

 Read (r): View the file’s contents or list a directory’s files.


 Write (w): Modify a file or add/delete files in a directory.
 Execute (x): Run a file as a program/script or enter a directory.
Letters Definition

'r' "read" the file's contents.

'w' "write", or modify, the file's contents.

"execute" the file. This permission is given


'x' only if the file is a program.

2. Ownership and Permission Groups


Permissions are assigned to three categories of users:

pg. 36 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

 User (Owner): The person who created the file.


 Group: Users belonging to a shared group (e.g., "developers" or
"admins").
 Others: Everyone else on the system.

File Permission: Operation Chart

Operators Definition

`+` Add permissions

`-` Remove permissions

pg. 37 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Operators Definition

`=` Set the permissions to the specified values

Note: All these permissions are being granted at three different levels based on their
group.
What are Permission Groups in Linux
First, you must think of those nine characters as three sets of three characters (see
the box at the bottom). Each of the three "rwx" characters refers to a different
operation you can perform on the file.
1. Owners: These permissions apply exclusively to the individuals who own
the files or directories.
2. Groups: Permissions can be assigned to a specific group of users,
impacting only those within that particular group.
3. All Users: These permissions apply universally to all users on the system,
presenting the highest security risk. Assigning permissions to all users
should be done cautiously to prevent potential security vulnerabilities.
--- --- ---
rwx rwx rwx
user group other

User, Group, and others Option in Linux File Permission

Reference Class Description

The user permissions apply


only to the owner of the file
or directory, they will not
impact the actions of other
`u` user users.

The group permissions


apply only to the group that
has been assigned to the file
`g` group
or directory, they will not

pg. 38 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Reference Class Description

affect the actions of other


users.

The other permissions


apply to all other users on
the system, this is the
permission group that you
`o` others want to watch the most.

All three (owner, groups,


`a` All three others)

How to Check the Permission of Files in Linux


Let's dive in to understand the possible methods to check all the desired details of a
file including "File Permission"

1. The "Trusty Command"

Here's the command to execute it within the terminal. Let's show you with an
example:
Input:
We're taking 'NarX' as a default file name:
ls -l [Link]
Output:
-rw-r--r-- 1 user group 46 Apr 14 16:37 [Link]
The above command represents these following information:
1. The first character = '-', which means it's a file 'd', which means it's a
directory.
2. The next nine characters = (rw-r--r--) show the security
3. The next column shows the owner of the file.
4. The next column shows the group owner of the file. (which has special
access to these files)

pg. 39 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

5. The next column shows the size of the file in bytes.


6. The next column shows the date and time the file was last modified.

2. The 'namei' Command

The 'namei' command is used to check the file path through layer of folder's path.
Here's the command to execute it within Terminal:
Here, we've taken 'path' as " root@anonymous-VirtualBox:~# " and file name as
"hoops"
namei -l /path/to/your/file

3. The 'stat' Command

Unlike 'ls -l' command, the "stat" command is used to pin point the file location.
Here's how you can do it:
We're taking file name as "hoops"
stat hoops
Output:
File: [Link]
Size: 2210 Blocks: 8 IO Block: 4096 regular file
Device: 802h/2050d Inode: 1288496 Links: 1
Access: 2024-11-18 10:50:56.000000000 +0000
Modify: 2024-11-18 10:50:56.000000000 +0000
Change: 2024-11-18 10:50:56.000000000 +0000
Birth: -

How to Change Permissions in Linux


The command you use to change the security permissions on files is called
"chmod", which stands for "change mode" because the nine security characters are
collectively called the security "mode" of the file. You can modify permissions
using symbolic notation or octal notation.

1. Symbolic Notation

Symbolic notation allows you to add, remove, or set permissions for specific users.
Let's understand this using different example below:
Example 1: To Change File Permission in Linux

pg. 40 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

If you want to give "execute" permission to the world ("other") for file "[Link]",
you will start by typing.
chmod o
Now you would type a '+' to say that you are "adding" permission.
chmod o+
Then you would type an 'x' to say that you are adding "execute" permission.
chmod o+x
Finally, specify which file you are changing.
chmod o+x [Link]
You can see the change in the picture below.

You can also change multiple permissions at once. For example, if you want to take
all permissions away from everyone, you would type.
chmod ugo-rwx [Link]
The code above revokes all the read(r), write(w), and execute(x) permission from all
user(u), group(g), and others(o) for the file [Link] which results in this.

pg. 41 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

chmod ugo

Example 2:
The code adds read(r) and write(w) permission to both user(u) and group(g) and
revoke execute(x) permission from others(o) for the file abc.mp4.
chmod ug+rw,o-x abc.mp4
Something like this:
chmod ug=rx,o+r abc.c
 Assigns read(r) and execute(x) permission to both user(u) and group(g)
and add read permission to others for the file abc.c.
 There can be numerous combinations of file permissions you can invoke
revoke and assign. You can try some on your Linux system.

2. Octal Notations Permissions in Linux

The octal notation is used to represent file permission in Linux by using three user
group by denoting 3 digits i.e.
 user
 group
 other users
Here's how to permissions are mapped:
 Read (r) = 4
 Write (w) = 2
 Execute (x) = 1

pg. 42 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Permissions for owner, group, and others are represented by a three-digit octal value.
The sum of permissions for each group gives the corresponding number.
Reference:
chmod o
Now you would type a '+' to say that you are "adding" permission.
chmod o+
Then you would type an 'x' to say that you are adding "execute" permission.
chmod o+x
Finally, specify which file you are changing.
chmod o+x [Link]
You can see the change in the picture below.

Octal Notations Permissions in Linux

 You can also change multiple permissions at once. For example, if you
want to take all permissions away from everyone, you would type.
chmod ugo-rwx [Link]
The code above revokes all the read(r), write(w), and execute(x) permission from all
user(u), group(g), and others(o) for the file [Link] which results in this.

pg. 43 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Octal Notations Permissions

Example:
The code adds read(r) and write(w) permission to both user(u) and group(g) and
revoke execute(x) permission from others(o) for the file abc.mp4.
chmod ug+rw,o-x abc.mp4
Something like this:
chmod ug=rx,o+r abc.c
 Assigns read(r) and execute(x) permission to both user(u) and group(g)
and add read permission to others for the file abc.c.
 There can be numerous combinations of file permissions you can invoke
revoke and assign. You can try some on your Linux system.
You can also use octal notations like this.

pg. 44 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

octal notations

 Using the octal notations table instead of 'r', 'w', and 'x'. Each digit octal
notation can be used for either of the group 'u', 'g', or'o'.
Security Permissions in Linux
The combination for the permissions are r,w,x, and -. Let's understand this briefly in
elaborative way:
For example: "rw- r-x r--"
 "rw-": the first three characters `rw-`. This means that the owner of the
file can "read" it (look at its contents) and "write" it (modify its contents).
We cannot execute it because it is not a program but a text file.
 "r-x": the second set of three characters "r-x". This means that the
members of the group can only read and execute the files.
 "r--": The final three characters "r--" show the permissions allowed to
other users who have a UserID on this Linux system. This means anyone
in our Linux world can read but cannot modify or execute the files'
contents.

pg. 45 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

Special Permissions in Linux


Besides usual methods, Linux also offers special permission types to have more
complex control over files.

1. The 'setuid' Command

The SET User ID permission allows user to execute programs with the previledges
of its owner. Below is the example for the same:
chmod u+s program

2. The 'setgid' Command

The Set Group ID permission allows files to run under fule's group permissions (or
ensures the files created in a directory inherits the group of the directory). Here's the
command for the same:
chmod g+s directoryname

3. The 'sticky bit' Command

This allows the user (only owner) to delete or rename files within the directory
(regardless of other user's permissions). Here's a command for the same:
chmod +t directoryname

How to Set File Permissions for a Specific User


To set permissions for a specific user or group:

1. By using chown
Use chown to change file ownsership:
chown user:group [Link]

2. By using chmod

Use chmod to modify permissions:


chmod 755 [Link]

pg. 46 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

File Management in Linux


File management in Linux involves handling files and directories through various
operations such as creation, modification, organization, and access control within the
filesystem.
 Linux treats everything as a file, including devices and system
configurations.
 Ensures efficient data organization and accessibility.
 Involves operations like create, copy, move, rename, and delete.
 Uses file permissions and ownership for secure access control.
 Common commands include cp, mv, rm, ls, cat, and chmod.
Linux categorizes files into three main types, each serving a specific purpose in the
system:

1. General Files

These are the most common file types that store user data such as text files, images,
and binaries.
 Represent regular data like documents, programs, or scripts.
 Can be created using the touch command.

pg. 47 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

 Form the majority of files in Linux/UNIX systems.


 May contain human-readable text (ASCII), executable binaries, or
program data.

2. Directories:

These act as containers that organize files and other directories hierarchically.
 Similar to folders in Windows.
 Store lists of file names and their related metadata.
 New directories can be created using the mkdir command.
Important directories include:
 /: Root directory (base of the system)
 /home/:User home directories
 /bin/: Essential user binaries
 /boot/: Static boot files

3. Device Files:

These files represent hardware devices and handle input/output (I/O) operations.
 Used to interact with physical devices like printers, disks, or terminals.
 Found mostly in the /dev/ directory.
 Allow the operating system to treat hardware as if it were a regular file.
Examples
The following examples illustrate common file management operations in Linux.

1. Listing Files

 To list files and directories in Linux, the ls command is used. It provides a


quick view of the contents of a directory, including files, subdirectories,
and optional details like permissions, ownership, and timestamps.
$ls

pg. 48 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

 Lists all files and directories in the current directory.


 Each type of file is displayed with a different color for easy identification.
 Directories are typically shown in dark blue.
 Helps visually distinguish between files, directories, and other file types.
 Makes navigating and understanding directory contents faster and more
intuitive.
Running ls -l returns a detailed listing of files and directories in the current
directory.
Command:
$ls -l
Output:

Displays important information such as:


 File permissions (who can read, write, or execute)
 Owner and group of each file
 File size and last modification date
 Helps determine which users or groups can access or manage each file,
providing insights into system security and file management.

2. Creating Files

 The touch command is used to create a new file in Linux.

pg. 49 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

 If the specified file does not exist, touch creates a new blank file.
 If the file already exists, its contents remain unaffected, and only the file’s
timestamp may be updated.
 This command is a quick and simple way to create empty files for various
purposes.
Example:
touch filename

3. Displaying File Contents

 The cat command is used to display the contents of a file in the terminal.
 Running cat filename shows the entire content of the specified file.
 For large files, the output may scroll past the screen too quickly; in such
cases, commands like more or less can be used to view the content page by
page.
Example:
cat filename

4. Copying a File

 The cp command is used to create a copy of a file in Linux.


 It copies the contents of the source file to a new file at the specified
destination.
 The new file will have the same name and content as the original, unless a
different name is specified.
Example:
cp source/filename destination/

pg. 50 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

5. Moving a File

 The mv command is used to move a file from one location to another in


Linux.
 It removes the file from the source directory and creates it in the
destination directory with the same name and content.
 This command can also be used to rename files by specifying a different
name at the destination.
Example:
mv source/filename destination/

6. Renaming a File

 The mv command can also be used to rename a file in Linux.


 It changes the file name from filename to new_filename while retaining
the file’s content.
 Essentially, the original file is replaced with a file of the new name
without altering the data.
mv filename new_filename

pg. 51 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE
SRI AKSHAYA DEGREE COLLEGE HOSPET

7. Deleting a File

 The rm command is used to delete a file in Linux.


 It permanently removes the specified file from the directory.
 Use this command carefully, as deleted files cannot be easily recovered.
rm filename

pg. 52 DEPT OF BCA UNIX SHELL SCRIPT NOTES 2 ND


MODULE

You might also like