Unix Shell Script Bca 4th Sem 2nd Module
Unix Shell Script Bca 4th Sem 2nd Module
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
}
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
getName(){
echo "$NAME (from function)"
}
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
#!/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:-
Below is the terminal shell pictorial depiction after executing the following
commands-
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
Options Description
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"
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
2. -p Option:
To view all exported variables on current shell.
Syntax:
$ export -p
Example:
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.
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.
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:
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
if(( $a==$b ))
then
echo a is equal to b.
else
echo a is not equal to b.
fi
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:
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
if(( ! $a == "true" ))
then
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
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
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:
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
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:
Explanation:
#/bin/bash: Specifies that the script should be interpreted using the Bash
shell.
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
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:
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.
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:
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.
<etc>
done
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:
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.
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:
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.
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:
Explanation:
Infinite Loop Structure:
1. while true: Initiates a while loop that continues indefinitely as the condition true
is always true.
2. Loop Body:
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.
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:
1. The if
2. The if...else...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
[[ "$str1" == "$str2" ]] True if strings are equal. (Note: == is an alias for = in [[...]])
-eq Equal
Example:
if [[ "$USER" == "root" && "$num" -gt 10 ]]; then echo "You are
root and the number is greater than 10."fi
Operators Definition
Operators Definition
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
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)
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
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: -
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
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.
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.
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
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.
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.
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.
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.
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
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
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
1. By using chown
Use chown to change file ownsership:
chown user:group [Link]
2. By using chmod
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.
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
2. Creating Files
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
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
5. Moving a File
6. Renaming a File
7. Deleting a File