0% found this document useful (0 votes)
16 views32 pages

SHELL Scripting Notes

Shell scripting involves writing commands in a text file for execution by the shell in Unix-like systems, automating repetitive tasks. It includes various components such as variables, loops, and conditional statements, and can be executed using different shell interpreters like Bourne shell and Bash. The document also covers topics like variable scope, command substitution, and control statements, providing syntax and examples for practical implementation.

Uploaded by

bhukyaashok123
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)
16 views32 pages

SHELL Scripting Notes

Shell scripting involves writing commands in a text file for execution by the shell in Unix-like systems, automating repetitive tasks. It includes various components such as variables, loops, and conditional statements, and can be executed using different shell interpreters like Bourne shell and Bash. The document also covers topics like variable scope, command substitution, and control statements, providing syntax and examples for practical implementation.

Uploaded by

bhukyaashok123
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

SHELL- SCRIPTING

[Link] SCRIPTING
 What is shell scripting?
 Shell scripting is the process of writing a series of commands in a text file that are executed by the shell,
which is a command-line interpreter in Unix or Unix-like operating systems.

 It is used to automate repetitive tasks by combining commands into a single script file that can be run to
perform those tasks sequentially.

 Shell scripts can contain variables, loops, conditional statements, functions, and comments.

 Shell scripting languages include Bourne shell (sh), Bash, C shell (csh), and others.

 Scripts typically have extensions like .sh and are run from the command line.
1. How to check how many shells available in our operating system?
Syntax:- cat/etc/shells

2. How to check default shells ?


Syntax:- echo $SHELL

3. How to check current shell ?


Syntax:- echo $0

Example:- mkdir script

cd script
mkdir batch9
cd batch9
cat [Link]
up time
date
hostname
1. BOURNE SHELL:- The Bourne shell (often called sh) is a fundamental command-line interpreter for Unix
systems, developed by Stephen Bourne at Bell Labs in 1979. It serves both as an interactive tool for command
execution and as a scripting environment for automating tasks.

Syntax:- sh

2. BOURNE AGAIN SHELL(BASH):- It is a advanced version of bourne shell and it is default version of
many linux flavour.

Syntax:- bsh,bash

1
 What is shell?

A shell is a user interface that provides access to the services of an operating system.

 How to execute any shell script ?

Syntax:- <shell name> <filename>

Example:- sh [Link]  Bourne shell

bash [Link]  bash shell

rbash [Link]  rbash shell

dash [Link]  dash shell

1. ./<filename>:- Default shell is responsible if you not give any shell name.

Example:- ./ [Link]

chmod u+x [Link]


./ [Link]

 In vi editor:-

Example:- vi [Link]
i  To navigate insert mode
call
hostname -i
df -h
ls -lrth
chmode u+x [Link]
./ [Link]
 For every shell script is .sh extension is mandatory to execute shell script?

Not mandatory.
 Why we generally use .sh extension all shell script?

For identification purpose.


 I want to always execute my given script by using bash only without mentioning shell name in front of
script name?

By using shebang at first line of a script.


Syntax:- #!|bin|sh

#!|bin|dash
#!|bin|bash

 What is shebang and what is the use of it?


By using shebang, we can specify interpreter which is responsible for execution of given script.

2
Example:- vi [Link]
i
#! |bin|bash
ps -ef | grep -i python
free -h
who am i
esc
:
wq
chmod u+x [Link]
./ [Link]
 Shebang is first line of shell script.

 If your script located at one place,if you want to execute that script from different location we have give
complete path after shell name,we have use below syntax.

Syntax:- shell name <complete path>/ script name

Exampe:- bash script|batch9|[Link]


cd ..|..|
cd Tomcat
bash script|batch9|[Link]
bash script|batch9|[Link]
bash script|batch9|[Link]
 Can i run my script from any location without giving complete path?
 Yes we can run my script from any location by using below sysntax.
Syntax:- echo $PATH
Example:- export PATH = $PATH : /home/ashok/script/batch9
bash [Link]
bash [Link]
bash [Link]
 The above script is sessional script not permanent script.
 How do i permanently add my script path to path variable?
Example:- ls -a
. bashrc
vi .bashrc
i

3
export PATH = $PATH : /home/ashok/script/batch9
esc
wq
3. .bashrc:- It is a startup file in linux
 ls -a  Shows hidden files in linux

2. VARIABLE
 Variables are place holders to hold values and it stores values.

 In shell script there are no data types, every value is treated as string/text type.

 Variables are used to store data such as numbers, text.

 Variables are two types, they are

[Link] variable

[Link] defined variable

[Link] variable

 In Shell scripting (sh, bash, ksh, etc.), there are many predefined (special) variables that the shell provides
automatically. These are sometimes called special parameters.

 You should not start variable names with numbers.

 We should no use special symbol in variable names like @,#,-,%,etc.

 If variable contain multiple words, then these words should be separated with _(Hifane) to separate the
words.

Example:- first_name = ashok

 How do we see content available in variable?

Syntax:- echo $<variable name>

Example:- x = 10 , name = ashok

echo $x (or) echo $name

[Link] defined variable

 These are variables created by the script writer to store data like strings, numbers, command outputs, or
user input.

Syntax:- variable_name = "some value"


echo $variable_name  Access value

4
Example:- name = "ASHOK"
age=25
greeting="Hello $name, you are $age years old."
echo $greeting
1. VARIABLE SCOPE:- Variable scope in shell scripting determines where a variable can be accessed
within a script, primarily distinguished as global and local scope.

 Types of variable scope:-


1. Session scope
2. User scope
3. System scope
1. Session Scope:-
 Variables set in a shell session (e.g., via terminal or a script) are only available while that session is
active.
 These variables are not exported to child processes or other sessions unless the export command is
used.
 Once the terminal or shell session is closed, variables in session scope are discarded.
[Link] Scope:-
 The variables which are mentioned inside .bashrc file are said to be user scope.
 The variable values are available for all sessions of current user
3. System Scope:-
 If variable available for all user and for all sessions and such type of variable said to be system scope.
Example:- vi .bashrc
first_name = BHUKYA
name = ASHOK
echo $ name
echo $ first_name

3. COMMAND SUBSTITUTION
1. Write a shell script to print present working directory?
cat > [Link]
pwd
ctrl+D
sh [Link]
 present working directory name is : path
vi [Link]
echo "present working directory is: $ (pwd)"
esc
:wq , bash [Link]
5
 We can execute command and we can substitute its result based on our requirement by using ‘command
substitution’.
2. Write a shell script which should display output like below?
1. Total [Link] files
2. Total [Link] directories
3. Total [Link] link files
vi [Link]
i
echo “total [Link] files : $ (ls -l | grep ‘^-’ | wc -l)”
echo “total [Link] link files : $ (ls -l | grep ‘^l’ | wc -l)”
echo “total [Link] directories : $ (ls -l | grep ‘^d’ | wc -l)”
esc
:wq
bash [Link]
3. Write a shell script to find out total [Link] lines is in given file [Link]?
vi [Link]
i
echo “total [Link] lines in [Link] : $ (wc -l [Link])”
esc
:wq
bash [Link]
4. total [Link] lines in [Link] file?
vi [Link]
i
echo “total [Link] lines in [Link] : $ (wc -l [Link])”
esc
:wq
bash [Link]
[Link] line argument:-The argument which are passing from the command prompt at the time of
execution our script is called as command line argument,
Syntax:- bash <args_example.sh> <arg1 arg2 arg3 ……..argn>
Example:- bash [Link] [Link]
vi [Link]
i
echo “total [Link] lines in $1 : $ (wc -l $1)”
esc

6
:wq
bash [Link] [Link]
bash [Link] [Link]
1. How do we check logs?
We can check logs by using more,less,grep,tail,etc.
2. How do we check rolling logs?
Syntax:- tail -f <filename>
Example:- vi [Link]
i
echo “1st file line $1 : $ (wc -l $1) ”
echo “2nd file line $2 : $ (wc -l $2) ”
echo “3rd file line $3 : $ (wc -l $3) ”
echo “script name : $0 ”
echo “all argument names : $* ”
echo “all argument names : $@ ”
echo “total [Link] command line arguments : $# ”
esc
:wq
cat [Link]
bash [Link] [Link] [Link] [Link]
$#  Total [Link] command line argument
$0  Script name itself
3. How do we access 1st argument inside script?
By using $1
4. How do you know whether given script is executed successful or not?
By using $?
5. Difference between $* and $@? Important

$* $@

All arguments are treated as a single string, joined by All arguments are treated as separate words.
the first character of the IFS (Internal Field
Separator, usually a space).
All arguments expanded as a single string with All arguments expanded as separate quoted
arguments joined by the first character of IFS. strings (each argument preserves its integrity).
When you want all arguments as one string (e.g., for When you want to preserve each argument as a
passing to a single command). separate word (commonly used in loops).

7
2. Passing dynamic input by using read command:-
The read command in a shell script is used to accept dynamic input from the user interactively
during the script’s execution. It reads one line of input from standard input (keyboard) and stores it into a
variable.
Syntax:- read <variable_name>
Example:- cat > ex_read.sh
read A
read B
echo $A
echo $B
ctrl + D
bash ex_read.sh
(enter some values in screen)
1. read -p:- The read -p command in shell scripting is used to display a prompt message to the user and then
read their input on the same line.
Syntax:- read -p "prompt message" <variable_name>
Example:- vi [Link]
i
read -p “enter name of student : ” Ashok
read -p “enter student roll number : ” 401
echo “student $Ashok got 565 marks and his roll number $401”
esc
:wq
cat [Link]
bash [Link]
1. Write a shell script to delete blank lines in a given file?
vi [Link]
i
add blank lines
esc
:wq
 To delete blank lines in [Link] file
vi [Link]
i
echo “we are removing blank lines in [Link] file”
sed -i ‘ /^$/d ’ [Link]

8
echo “ blank lines are removed from [Link] file ”
esc
:wq
cat [Link]
cat >> [Link]
hi
linux
sql
ctrl + D
bash [Link]
cat [Link]
cat [Link]
2. To delete blank lines using read -p command?
case1:-
vi [Link]
i
read -p “ enter filename : ” file
echo “ we are removing blank lines in $file file ”
sed -i ‘ /^$/d ’ $file
echo “ blank lines are removed from $file file ”
esc
:wq
cat [Link]
cat [Link]
bash [Link]
enter filename : [Link]
case2:-
cat > [Link]
read -p “enter your account number : ” A
read -p “ enter your password : ” P
echo “ your account number is $A and your balance is 1000 ”
ctrl +D
bash [Link]
 If you want to do not display password when you are enter : password
2. read -s:- If you want to hide input on screen which provided by end user.

9
Syntax:- read -s <variable_name>
Example:- vi [Link]
i
read -p “ enter your account number : ” A
read -s -p “ enter your password: ” P
echo “ your account number is $A and your balane is 1000 ”
esc
:wq
cat [Link]
bash [Link]

4. OPERATORS
In shell scripting, operators are symbols or keywords used to perform operations on variables and
values. These operators enable arithmetic calculations, comparisons, logical decisions, and file tests within
scripts.
Operator Type Description Examples
Arithmetic Operators Used for mathematical +, -, *, /, %, ++, --
calculations on numbers.
Relational Operators Compare two numbers and return -eq (equal), -ne (not equal), -
true or false. lt (less than), -le (less or equal), -
gt (greater than), -ge (greater or
equal)
Boolean (Logical) Operators Perform logical operations, often ! (NOT), -a (AND), -o (OR), &&,
used in conditions. `
String or Assignment Operators Compare strings = (equal), != (not equal), <, >

File Test Operators Test file types and attributes -e (exists), -f (is file), -d (is
(existence, readability, directory, directory), -r (readable), -
etc.) w (writable), -x (executable)
Bitwise Operators Operate on bit-level (rarely used &, `
in shell scripting)
1. What is the difference between = and -eq?
 (=) If you want assign any value then we use assignment operator.
 -eq will be used to compare two numeric values.
Example:- a = 10
b = 20
echo $a
echo $b
 add two values
c = $a +$b
echo $c

10
2. How to perform mathematical operations?
 By using ‘expr’ keyword
 By using ‘let’ keyword
 By using (( ))
 By using [ ]
 By using (( )):-
c = $(($a + $b))
echo $c
d = $ ((a + b))
echo $d
 By using [ ]:-
1) $ [$v1 + $v2]:-
Example:- e = $ [$a + $b]
echo $e
2) # [v1 + v2]:-
Example:- f = $ [a + b]
echo $f
1. CONTROL STATEMENTS:- Control statements in shell scripting are used to manage the execution flow
of commands based on conditions or for repetitive tasks. The primary types are conditional statements and
loop statements, enabling dynamic and flexible script logic.
 Types of control statements:
1. Conditional Statements:-
1. if statement: Executes code if a condition is true.
Example:- if [ condition ]; then
commands
fi
2. case statement: Works like a switch-case, matching a variable with patterns and executing
matched commands.
Example:- case $variable in
pattern1) commands1 ;;
pattern2) commands2 ;;
*) default_commands ;;
esac
Types of if statements:-
1. Simple if 2. if-else 3. nested if 4. ladder if
1. Simple if:- A simple if statement in shell scripting allows conditional execution of commands
when a specified condition is true.
Example:- if [ condition ]; then

11
action1
else
action2
fi
case 1:- Take input from user check it is positive or negative number, if it is positive, print positive otherwise
print negative?
cs script/batch9
vi if_1.sh
i
#!/bin/bash
read -p "Enter your number: " n
if [ "$n" -ge 0 ]; then
echo "Given number is positive number"
else
echo "Given number is negative number"
fi
esc
:wq
bash if_1.sh
enter numeric positive or negative number:
2. if-else :- Executes code in the else block if the condition is false.
Example:- if [ condition ]; then
commands
else
other_commands
fi
3. Nested if :- A nested if statement in shell scripting is an if statement placed inside another if
statement. It allows for more complex decision-making by enabling multiple condition checks, one
inside another.
Example:- if [ condition1 ]; then
# commands if condition1 is true
if [ condition2 ]; then
# commands if condition2 is also true
else
fi
else

12
fi
case1:- Take input from user to check he is giving valid age or not, if not print like give valid age otherwise
check if age > 18 then print ‘eligible for voter id’ else print ‘not eligible for voter id’?
vi nsif_1.sh
i
read -p "Enter your age: " age
if [ $age -ge 0 ]; then
if [ $age -gt 18 ]; then
echo "Eligible for voter id"
else
echo "Not eligible for voter id"
fi
else
echo "Please enter a valid age"
fi
esc
:wq
cat nsif_1.sh
bash nsif_1.sh
enter your age:
4. ladder if:- Checks multiple conditions in sequence.
Example:- if [ condition1 ]; then
# commands if condition1 is true
elif [ condition2 ]; then
# commands if condition2 is true
elif [ condition3 ]; then
# commands if condition3 is true
else
# commands if none of the above conditions are true
fi
case 1:-
vi lad_1.sh
i
read -p " enter your marks : " m
if [ $m -gt 500 ]
then
13
echo " you got first class "
elif [ $m -le 500 -a $m -ge 400 ]
then
echo " you got second class "
elif [ $m -lt 400 ]
then
echo " you got third class "
else
echo " please enter valid marks "
fi
esc
:wq
cat lad_1.sh
bash lad_1.sh
enter your marks:
case 2:- Take a input from user if it is even number print like given number is even otherwise print given
number like odd number?
vi even_1.sh
i
read -p "Enter your number: " n
if [ $((n % 2)) -eq 0 ]; then
echo "Given number is an even number"
else
echo "Given number is an odd number"
fi
esc
:wq
cat even_1.sh
bash even_1.sh
enter your number:

2. Looping/Iteration Statements:-
1. for loop: Repeats commands for each value in a list.
Example:- for var in list; do
commands
done
14
2. while loop: Repeats commands while a condition is true.
Example:- while [ condition ]; do
commands
done
3. until loop: Repeats commands until a condition becomes true.
Example:- until [ condition ]; do
commands
done
4. break: Exits a loop prematurely.
5. continue: Skips the rest of the current loop iteration and proceeds to the next.
2. FILE TEST CONDITIONS:- n shell scripting, file test conditions are special operators used to check various
attributes of files and directories. These operators are commonly used in if statements to test properties like
existence, type, permissions, size, and more.
Operator Description
-e file Checks if the file exists (true for any type)
-f file Checks if the file is a regular file
-d file Checks if the file is a directory
-r file Checks if the file is readable
-w file Checks if the file is writable
-x file Checks if the file is executable
-s file Checks if the file size is greater than zero
-b file Checks if the file is a block special file
-c file Checks if the file is a character special file
-p file Checks if the file is a named pipe (FIFO)
-L file Checks if the file is a symbolic link
-S file Checks if the file is a socket

Example 1:- Take a input from the user and check is there any files/directories available with given name?
vi file_dir.sh
i
read -p " enter your file/directory name : " test
if [ -e $test ]; then
echo " given name file/directory is exists "
else
echo " given name file/directory does not exists "
fi
esc
:wq

15
cat file_dir.sh
bash file_dir.sh
Example 2:- Write a script and take input from user and check weather it is a file, directory or link file. If no
file/directory exist with that name then display like no file/directory exist?
vi link_file_dir.sh
i
read -p "Enter your file/directory name: " test2
if [ -e "$test2" ]; then
if [ -f "$test2" ]; then
echo "It is a regular file"
elif [ -d "$test2" ]; then
echo "It is a directory"
elif [ -L "$test2" ]; then
echo "It is a link file"
fi
else
echo "With the given name, file/directory does not exist"
fi
esc
:wq
cat link_file_dir.sh
bash link_file_dir.sh
enter your file/directory name:
Example 3:- If it is afile we need to check whether it is empty or non empty file?
cp link_file_dir.sh file2_dir.sh
vi file2_dir.sh
i
read -p "Enter your file/directory name: " test3
if [ -e "$test3" ]; then
if [ -f "$test3" ]; then
if [ -s "$test3" ]; then
echo "It is a non-empty file"
else
echo "It is an empty file"
fi
elif [ -d "$test3" ]; then
16
echo "It is a directory"
elif [ -L "$test3" ]; then
echo "It is a link file"
else
echo "It is a file"
fi
else
echo "With the given name, file/directory does not exist"
fi
esc
:wq
cat file2_dir.sh
bash file2_dir.sh
enter your file/directory name:
Example 4:- Write a shell script and take two strings as input from user and compare two strings are same or
not?
vi [Link]
i
read -p " Enter first string : " string1
read -p " Enter second string : " string2
if [ $string1 = $string2 ]; then
echo " Both strings are same "
else
echo " Both strings are not same "
fi
esc
:wq
cat [Link]
bash [Link]
Enter first string name: ashok
Enter second string name: ashok
Example 5:- Write a shell script to identify zombie process are exist or not?
 To check zombie process
Syntax:- ps -aux | grep -w z
vi [Link]
i
17
zombie=$(ps aux | grep -w Z | grep -v grep)
count=$(echo "$zombie" | wc -l)
if [ -z "$zombie" ]; then
echo "There are no zombie processes in our system"
else
echo "There are zombie processes in our system"
fi
esc
:wq
cat [Link]
bash [Link]
Example 6:- How to kill zombie process in shell script?
vi zombie_kill.sh
i
#!/bin/bash
# Count the number of zombie processes (with STAT column as Z)
zombie_count=$(ps aux | awk '$8=="Z" {print}' | wc -l)
echo "Zombie process count: $zombie_count"
if [ "$zombie_count" -ge 1 ]; then
echo "There are zombie processes in our system."
# Get the PIDs of the zombie processes
zombie_pids=$(ps aux | awk '$8=="Z" {print $2}')
# For each zombie PID, find its parent and try to notify the parent to clean up
for pid in $zombie_pids; do
parent_pid=$(ps -o ppid= -p $pid | tr -d ' ')
echo "Killing zombie PID: $pid, notifying parent PID: $parent_pid"
# Send SIGCHLD to parent process to prompt cleanup
kill -s SIGCHLD $parent_pid
# Optionally, if the zombie persists, forcibly kill the parent
sleep 1
if ps -p $pid > /dev/null; then
echo "Zombie $pid still exists, killing parent $parent_pid"
kill -9 $parent_pid
else
echo "Zombie $pid has been cleaned up."

18
fi
done
else
echo "There are no zombie processes in our system."
fi
esc
:wq
cat zombie_kill.sh
bash zombie_kill.s
[Link] WE NEED TO USE LOOPS:- Loops are essential in shell scripting because they allow the repeated
execution of commands, enabling automation of repetitive tasks such as processing lists of files, iterating over
arrays, and handling user inputs efficiently.
Benefits of Using Loops
 Automate routine and repetitive tasks, saving manual effort and reducing errors.
 Efficiently process collections of items, such as files or data entries.
 Minimize code duplication by using repetition structures instead of writing commands multiple times.
 Improve script readability, maintainability, and adaptability to different situations.
Types of Loops in Shell Scripts
1. While loop:- If we don’t know number of iterations in advance, then we should use while loop.
Syntax:- while [ condition ]
do
command1
command2
# ... more commands
done
 As long as given condition true, then body of while loop will be executed.
 Once condition fails then only loop will be terminated.
Example 1:- Print 1 to 5 numbers?
vi while_1.sh
i
#!/bin/bash
count=1
while [ $count -le 5 ]
do
echo $count
count=$((count + 1))
done

19
esc
:wq
cat while_1.sh
bash while_1.sh
Example 2:- Take a input from the user and print numbers till that numbers?
vi while_2.sh
i
#!/bin/bash
read -p "Enter a number: " n
count=1
while [ $count -le $n ]
do
echo $count
let count++
done
esc
:wq
cat while_2.sh
bash while_2.sh
1. Sleep command:- The sleep command in a shell script is used to pause the execution for a specified amount
of time. This lets you introduce delays or wait between commands in your script.
Syntax:- sleep NUMBER[SUFFIX]
Example 1:- Sleep for 2 seconds?
vi while_3.sh
i
#!/bin/bash
read -p "Enter a number: " n
count=1
while [ $count -le $n ]
do
echo $count
sleep 2
let count++
done
esc
:wq
20
cat while_3.sh
bash while_3.sh
Example 2:- Print only even numbers?
vi while_even.sh
i
#!/bin/bash
read -p "Enter your number : " n
i=1
while [ $i -le $n ]
do
if [ $((i % 2)) -eq 0 ]
then
echo $i
fi
let i++
done
esc
:wq
cat while_even.sh
bash while_even.sh
Example 3:- Print even numbers with 2 seconds delay time?
vi even_sleep.sh
i
#!/bin/bash
read -p "Enter your number : " n
i=1
while [ $i -le $n ]
do
if [ $((i % 2)) -eq 0 ]
then
echo $i
sleep 2
fi
let i++
done

21
esc
:wq
cat even_sleep.sh
bash [Link]
Example 4:- Print odd numbers?
vi while_odd.sh
i
#!/bin/bash
read -p "Enter your number : " n
i=1
while [ $i -le $n ]
do
if [ $((i % 2)) -ne 0 ]
then
echo $i
fi
let i++
done
esc
:wq
cat while_odd.sh
bash while_odd.sh
Example 5:- Print odd numbers with 2 seconds time delay?
vi odd_sleep.sh
i
#!/bin/bash
read -p "Enter your number : " n
i=1
while [ $i -le $n ]
do
if [ $((i % 2)) -ne 0 ]
then
echo $i
sleep 2
fi

22
let i++
done
esc
:wq
cat odd_sleep.sh
odd_sleep.sh
2. Break command:- Based on some conditions if we want to braek loop (To come out from loop) then we
should use break statement.
Syntax:- break N
Example 1:- Using break in a while loop?
vi while_break.sh
i
#!/bin/bash
count=1
while [ $count -le 10 ]
do
echo $count
if [ $count -eq 6 ]; then
break
fi
((count++))
done
echo "While loop terminated"
esc
:wq
cat while_break.sh
bash while_break.sh
Example 2:- Using break in a for loop?
vi for_break.sh
i
#!/bin/bash
for i in {1..10}
do
if [ $i -eq 4 ]; then
break
fi
23
echo $i
done
echo "For loop terminated"
esc
:wq
cat for_break.sh
bash for_break.sh
3. Continue command:- We can use continue statement to skip current iteration and continue for next iteration.
Syntax:-
continue N
Example 1:- Using continue statement in while loop?
vi while_continue.sh
i
#!/bin/bash
read -p "Enter your number : " n
i=0
while [ $i -lt $n ]
do
let i++
if [ $((i % 2)) -eq 0 ]; then
continue
fi
echo "$i"
done
esc
:wq
cat while_continue.sh
bash while_continue.sh
Example 2:- Using continue statement in for loop?
vi for_continue.sh
i
#!/bin/bash
read -p "Enter your number : " n
for (( i=1; i<=n; i++ ))
do

24
if [ $((i % 2)) -eq 0 ]; then
continue
fi
echo "$i"
done
esc
:wq
cat for_continue.sh
bash for_continue.sh
Example 3:- How to read file name from user and count [Link] characters in each line?

vi read_line.sh
i vi read_l.sh
#!/bin/bash i
read -p "Enter the file name: " filename read -p “Enter file name: “ test
if [ ! -f "$filename" ]; then i=1
echo "File not found!" while read -r line
exit 1 do
fi echo “$line” | wc -c
while IFS= read -r line i=$((i+1))
do (or) done < "$test"
length=${#line} esc
echo "Line: $line" :wq
echo "Number of characters: $length" cat read_l.sh
done < "$filename" bash read_l.sh
esc Enter file name:
:wq
cat read_line.sh
bash read_line.sh
Enter the file name:

2. For loop: Iterates over a list or a range, useful for processing multiple items like filenames or numbers.
Syntax:- for variable in list
do
# commands to execute for each item in the list
done
Example 1:- print 1 to 5 values?
vi [Link]
i
for i in 1 2 3 4 5
do
echo $i

25
done
esc
:wq
cat [Link]
bash [Link]
Example 2:- Print 1 to 15 numbers?
vi [Link]
i
for i in {1..50}
do
echo $i
done
esc
:wq
cat [Link]
bash [Link]
Example 3:- Print 1 to 20 numbers with 1sec time delay?
vi for2_sleep.sh
i
for i in {1..20}
do
echo $i
sleep 1
done
esc
:wq
cat for2_sleep.sh
bash for2_sleep.sh
Example 4:- how to print names with phone numbers in shell script using for loop?
vi for_names.ss
i
#!/bin/bash
# Define arrays with names and phone numbers
names=("Ashok" "Bodi" "Baburao" "Kalyani" "Vani")
phones=("9515787562" "9949529653" "9866614016" "9542148103" "9849427130")

26
# Loop through the indices of the arrays
for i in "${!names[@]}"
do
echo "Name: ${names[i]}, Phone: ${phones[i]}"
done
esc
:wq
cat for_names.sh
bash for_names.sh
Example 5:- how to print names after phone numbers with 1sec time delay in shell script using for loop?
vi for_names_sleep.sh
i
esc
#!/bin/bash
names=("Ashok" "Bodi" "Baburao" "Kalyani" "Vani")
phones=("9515787562" "9949529653" "9866614016" "9542148103" "9849427130")
for i in "${!names[@]}"
do
echo "Name: ${names[i]}"
sleep 2
echo "Phone: ${phones[i]}"
done
esc
:wq
cat for_names_sleep.sh
bash for_names_sleep.sh
Example 6:- how to print names after phone numbers with 1sec time delay in shell script using for loop with
names and phone numbers are different colors?
vi for_color_names.sh
i
#!/bin/bash
# Define color codes using ANSI escape sequences
RED='\033[0;31m' # Red for phone numbers
GREEN='\033[0;32m' # Green for names
NC='\033[0m' # No Color (reset)
# Arrays with phone numbers and names
27
names=("Ashok" "Bodi" "Baburao" "Kalyani" "Vani")
phones=("9515787562" "9949529653" "9866614016" "9542148103" "9849427130")
for i in "${!phones[@]}"
do
# Print name in green
echo -e "${GREEN}Name: ${names[i]}${NC}"
# Wait for 2 second
sleep 2
# Print phone number in red
echo -e "${RED}Phone: ${phones[i]}${NC}"
done
esc
:wq
cat for_color_names.sh
bash for_color_names.sh
Example 7:- Print all files and directories in pwd?
vi [Link]
i
for i in $(ls)
do
echo "$i"
done
esc
:wq
cat [Link]
bash [Link]
Example 8:- print all files and directories in pwd in shell script using for loop and files are orange color and
directories are red colors?
vi file_dir_color.sh
i
#!/bin/bash
# ANSI color codes
RED='\033[0;31m' # Red for directories
ORANGE='\033[0;33m' # Orange (Brown/Yellow) for files
NC='\033[0m' # No Color / Reset
for item in *
28
do
if [ -d "$item" ]; then
echo -e "${RED}$item${NC}"
else
echo -e "${ORANGE}$item${NC}"
fi
done
esc
:wq
cat file_dir_color.sh
bash file_dir_color.sh
Example 9:- Write a shell script to read the content of any file?
vi [Link]
i
read -p " Enter any file name : " test
for i in $(cat "$test")
do
echo $i
done
esc
:wq
cat [Link]
bash [Link]
Example 10:- Write a shell script to read the content of any directory?
vi [Link]
i
#!/bin/bash
# Prompt user to enter directory path
read -p "Enter the directory path: " dir_path
# Check if the directory exists
if [ -d "$dir_path" ]; then
echo "Contents of $dir_path:"
# List the contents of the directory
for entry in "$dir_path"/*; do
echo "$(basename "$entry")"

29
done
else
echo "Directory does not exist."
fi
esc
:wq
cat [Link]
bash [Link]
Example 11:- Write a shell script to read the content of any file and directory?
vi read_file_dir.sh
i
#!/bin/bash
# Read file contents
read -p "Enter the file path to read: " file_path
if [ -f "$file_path" ]; then
echo "Contents of file $file_path:"
while IFS= read -r line
do
echo "$line"
done < "$file_path"
else
echo "File does not exist."
fi
echo ""
# Read directory contents
read -p "Enter the directory path to list: " dir_path
if [ -d "$dir_path" ]; then
echo "Contents of directory $dir_path:"
for entry in "$dir_path"/*
do
echo "$(basename "$entry")"
done
else
echo "Directory does not exist."
fi

30
esc
:wq
cat read_file_dir.sh
bash read_file_dir.sh
Example 12:- Write a shell script to take path from user and rename like, if it is file then file_name, dir_name,
link_name?
vi [Link]
i
read -p "Enter your path: " path
cd "$path" || { echo "Directory not found."; exit 1; }
for i in $(ls); do
if [ -f "$i" ]; then
mv "$i" "file_$i"
elif [ -d "$i" ]; then
mv "$i" "dir_$i"
elif [ -L "$i" ]; then
mv "$i" "link_$i"
fi
done
esc
:wq
cat [Link]
bash [Link]
Example 13:- Write a shell script for move files to backup directory which stuck more than one day?
vi mv_backup.sh
i
find script/-maxdepth 1 -type f -mtime +1 -exec mv {} /home/ashok/script_backup\;
esc
:wq
cat mv_backup.sh
mkdir script_backup
bash mv_backup.sh
Example 14:- Test given pattern available in file if it is available then print like ‘ pattern is available ’ otherwise
priny ‘ no pattern is available ’?
vi [Link]
i

31
read -p “ Enter your filename : ” file
read -p “ Enter your pattern name : ” pattern
if grep -q $pattern $file
then
echo “ Given pattern is available in $file ”
else
echo “ Given pattern is not available in $file ”
esc
:wq
cat [Link]
bash [Link]

32

You might also like