SlideShare a Scribd company logo
Shell Script
How do you run a shell script from the command line?
To run a shell script from the command line, we need to
follow these steps:
•Make sure the script file has executable permissions using
the chmod command:
chmod +x myscript.sh
•Execute the script using its filename:
./myscript.sh
#!/bin/bash
#Creates a new variable with a value of "Hello World“
learningbash="Hello World"
echo $learningbash
The first line (/bin/bash) is used in every bash script. It instructs the operating system
to use a bash interpreter as a command interpreter.
Hello World is the most simple bash script to start with. We will create a new variable
called learningbash and print out the words Hello World. First, open a new shell script file with a
text editor of your choice
What is the difference between single quotes (‘) and double quotes (“) in shell
scripting?
Single quotes (‘) and double quotes (“) are used to enclose strings in shell scripting, but
they have different behaviors:
•Single quotes: Everything between single quotes is treated as a literal string. Variable
names and most special characters are not expanded.
•Double quotes: Variables and certain special characters within double quotes are
expanded. The contents are subject to variable substitution and command substitution.
#!/bin/bash
abcd=”Hello”
echo ‘$abcd’ # Output: $abcd
echo “$abcd” # Output: Hello
#!/bin/bash
#Creates a new variable
date=“Monday”
echo ‘$date’
echo “$date”
echo `date`
#!/bin/bash
echo "What is your age?"
read age
echo "Wow, you look younger than $age years old"
Get User Input
To take input from users, we’ll use the read bash command. First, create a
new bash shell file
How can you use command-line arguments in a shell script?
Command-line arguments are values provided to a script when it’s executed. They can be accessed within
the script using special variables like $1, $2, etc., where $1 represents the first argument, $2 represents the
second argument, and so on.
For Example: If our script name in `example.sh`
#!/bin/bash
echo “Script name: $0”
echo “First argument: $1”
echo “Second argument: $2”
Conditional Statements
The most popular and widely used conditional statement is if. Even though the if statement is
easy to write and understand, it can be used in advanced shell scripts as well.
#!/bin/bash
salary=1000
expenses=800
#Check if salary and expenses are equal
if [ $salary == $expenses ]
then
echo "Salary and expenses are equal" #Check if salary and
expenses are not equal
elif [ $salary != $expenses ]
then
echo "Salary and expenses are not equal"
fi
Check if a Number is Even or Odd
Odd and even numbers can be easily divided using the if statement and some simple math.
Create a file named evenoddnumbers.sh
#!/bin/bash
read -p "Enter a number and I will check if its odd or even " mynumber
if [ $((mynumber%2)) -eq 0 ]
then
echo "Your number is even"
else
echo "Your number is odd."
fi
#!/bin/bash
read -p "Please enter your choice: " response
## If the response given did not consist entirely of digits
if [[ ! $response =~ ^[0-9]*$ ]]
then
## If it was Quit or quit, exit
[[ $response =~ [Qq]uit ]] && exit
## If it wasn't quit or Quit but wasn't a number either,
## print an error message and quit.
echo "Please enter a number between 0 and 100 or "quit" to exit" && exit
Fi
## Process the other choices
if [ $response -le 59 ]
then
echo "F"
elif [ $response -le 69 ]
then
echo "D"
elif [ $response -le 79 ]
then
echo "C"
elif [ $response -le 89 ]
Then
echo "B"
elif [ $response -le 100 ]
then
echo "A"
elif [ $response -gt 100 ]
then
echo "Please enter a number between 0 and 100"
exit
fi
Loops
A loop is an essential tool in various programming languages. To put it simply,
a bash loop is a set of instructions that are repeated until a user-specified
condition is reached. Start by creating a loop bash program:
#!/bin/bash
n=0
while :
do
echo Countdown: $n
((n++))
done
This will work as a
countdown to infinity until
you press CTRL + C to stop
the script.
#!/bin/bash
for (( n=2; n<=10; n++ ))
do
echo "$n seconds"
done
Create an Array
A bash array is a data structure designed to store information in an indexed way. It is extra
useful if users need to store and retrieve thousands of pieces of data fast. What makes bash
arrays special is that unlike any other programming language, they can store different types
of elements. For example, you can use a bash array to store both strings and numbers.
#!/bin/bash
# Create an indexed array
IndexedArray=(egg burger milk)
#Iterate over the array to get all the values
for i in "${IndexedArray[@]}";do echo "$i";done
Generate Factorial of Number
#!/bin/bash
echo Enter the number you want to get factorial
read mynumber
factorial=1
for ((i=1;i<=mynumber;i++))
do
factorial=$(($factorial*$i))
done
echo $factorial
#!/bin/bash
echo "Enter a number:"
read number
i=2
if [ $number -lt 2 ]
then
echo "$number is not a prime number."
exit
fi
while [ $i -lt $number ]
do
if [ `expr $number % $i` -eq 0 ]
then
echo "$number is not a prime number."
exit
fi
i=`expr $i + 1`
done
echo "$number is a prime number."
Shell Script to Check Prime Number
#!/bin/bash
echo "Enter a number:"
read number
i=2
if [ $number -lt 2 ]
then
echo "$number is not a prime number."
exit
fi
max=`echo "sqrt($number)" | bc`
while [ $i -le $max ]
do
if [ `expr $number % $i` -eq 0 ]
then
echo "$number is not a prime number."
exit
fi
i=`expr $i + 1`
done
echo "$number is a prime number."
#!/bin/bash
echo "Enter a number"
read num
reverse=0
while [ $num -gt 0 ]
do
remainder=$(( $num % 10 ))
reverse=$(( $reverse * 10 + $remainder ))
num=$(( $num / 10 ))
done
echo "Reversed number is : $reverse"
Script for reversing a number
# Program to print the
# given pattern
# Static input for N
N=5
# variable used for
# while loop
i=0
j=0
while [ $i -le `expr $N - 1` ]
do
j=0
while [ $j -le `expr $N - 1` ]
do
if [ `expr $N - 1` -le `expr $i + $j` ]
then
# Print the pattern
echo -ne "#"
else
# Print the spaces required
echo -ne " "
fi
j=`expr $j + 1`
done
# For next line
echo
i=`expr $i + 1`
done
Output:
#
##
###
####
#####
Functions
A bash function is a set of commands that can be reused numerous times
throughout a bash script.
#!/bin/bash
hello () {
echo 'Hello World!’
}
hello
Display String Length
#!/bin/bash
# Create a new string
mystring="lets count the length of this string"
i=${#mystring}
echo "Length: $i"
Extract String
#!/bin/bash
cut -d , -f 5 <<< "Website,Domain,DNS,SMTP,5005"
#!/bin/bash
expr substr "458449Hostinger4132" 7 9
Find and Replace String
#!/bin/bash
first="I drive a BMW and Volvo"
second="Audi"
echo "${first/BMW/"$second"}"
Concatenate Strings
#!/bin/bash
firststring="The secret is..."
secondstring="Bash"
thirdstring="$firststring$secondstring"
echo "$thirdstring"
#!/bin/bash
firststring="The secret is..."
firststring+="Bash"
echo "$firststring"
Read Files
#!/bin/bash
myvalue=`cat mysamplefile.txt`
echo "$myvalue"
Print Files With Line Count
#!/bin/bash
myfile='cars.txt’
i=1
while read lines;
do
echo "$i : $lines"
i=$((i+1))
done < $myfile
Delete Files
#!/bin/bash
myfile='cars.txt’
touch $myfile
if [ -f $myfile ]; then
rm cars.txt
echo "$myfile deleted"
fi
Test if File Exists
#!/bin/bash
MyFile=cars.txt
if [ -f "$MyFile" ]; then
echo "$MyFile exists."
else
echo "$MyFile does not exist.“
fi
Ad

More Related Content

Similar to Operating_System_Lab_ClassOperating_System_2.pdf (20)

LBQbzhdhd dhdudjeh djdidjehr-Udemy 2.pptx
LBQbzhdhd dhdudjeh djdidjehr-Udemy 2.pptxLBQbzhdhd dhdudjeh djdidjehr-Udemy 2.pptx
LBQbzhdhd dhdudjeh djdidjehr-Udemy 2.pptx
SthitaprajnaBiswal1
 
Shell Scripting Intermediate - RHCSA+.pdf
Shell Scripting Intermediate - RHCSA+.pdfShell Scripting Intermediate - RHCSA+.pdf
Shell Scripting Intermediate - RHCSA+.pdf
RHCSA Guru
 
Bash shell
Bash shellBash shell
Bash shell
xylas121
 
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaaShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ewout2
 
Shell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdfShell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdf
HIMANKMISHRA2
 
Bash and regular expressions
Bash and regular expressionsBash and regular expressions
Bash and regular expressions
plarsen67
 
ShellAdvanced shell scripting programm.ppt
ShellAdvanced shell scripting programm.pptShellAdvanced shell scripting programm.ppt
ShellAdvanced shell scripting programm.ppt
ubaidullah75790
 
Shell programming
Shell programmingShell programming
Shell programming
Moayad Moawiah
 
Bash
BashBash
Bash
KLabCyscorpions-TechBlog
 
Advanced linux chapter ix-shell script
Advanced linux chapter ix-shell scriptAdvanced linux chapter ix-shell script
Advanced linux chapter ix-shell script
Eliezer Moraes
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Unix Shell Programming subject shell scripting ppt
Unix Shell Programming subject shell scripting pptUnix Shell Programming subject shell scripting ppt
Unix Shell Programming subject shell scripting ppt
Radhika Ajadka
 
Abs guide
Abs guideAbs guide
Abs guide
Sankara Narayanan A
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
mugeshmsd5
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Mufaddal Haidermota
 
Bash and regular expressions
Bash and regular expressionsBash and regular expressions
Bash and regular expressions
plarsen67
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
Gaurav Shinde
 
Shell scripting _how_to_automate_command_l_-_jason_cannon
Shell scripting _how_to_automate_command_l_-_jason_cannonShell scripting _how_to_automate_command_l_-_jason_cannon
Shell scripting _how_to_automate_command_l_-_jason_cannon
Syed Altaf
 
Shell Programming Language in Operating System .pptx
Shell Programming Language in Operating System .pptxShell Programming Language in Operating System .pptx
Shell Programming Language in Operating System .pptx
SherinRappai
 
OS.pdf
OS.pdfOS.pdf
OS.pdf
ErPawanKumar3
 
LBQbzhdhd dhdudjeh djdidjehr-Udemy 2.pptx
LBQbzhdhd dhdudjeh djdidjehr-Udemy 2.pptxLBQbzhdhd dhdudjeh djdidjehr-Udemy 2.pptx
LBQbzhdhd dhdudjeh djdidjehr-Udemy 2.pptx
SthitaprajnaBiswal1
 
Shell Scripting Intermediate - RHCSA+.pdf
Shell Scripting Intermediate - RHCSA+.pdfShell Scripting Intermediate - RHCSA+.pdf
Shell Scripting Intermediate - RHCSA+.pdf
RHCSA Guru
 
Bash shell
Bash shellBash shell
Bash shell
xylas121
 
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaaShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ewout2
 
Shell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdfShell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdf
HIMANKMISHRA2
 
Bash and regular expressions
Bash and regular expressionsBash and regular expressions
Bash and regular expressions
plarsen67
 
ShellAdvanced shell scripting programm.ppt
ShellAdvanced shell scripting programm.pptShellAdvanced shell scripting programm.ppt
ShellAdvanced shell scripting programm.ppt
ubaidullah75790
 
Advanced linux chapter ix-shell script
Advanced linux chapter ix-shell scriptAdvanced linux chapter ix-shell script
Advanced linux chapter ix-shell script
Eliezer Moraes
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Unix Shell Programming subject shell scripting ppt
Unix Shell Programming subject shell scripting pptUnix Shell Programming subject shell scripting ppt
Unix Shell Programming subject shell scripting ppt
Radhika Ajadka
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
mugeshmsd5
 
Bash and regular expressions
Bash and regular expressionsBash and regular expressions
Bash and regular expressions
plarsen67
 
Shell scripting _how_to_automate_command_l_-_jason_cannon
Shell scripting _how_to_automate_command_l_-_jason_cannonShell scripting _how_to_automate_command_l_-_jason_cannon
Shell scripting _how_to_automate_command_l_-_jason_cannon
Syed Altaf
 
Shell Programming Language in Operating System .pptx
Shell Programming Language in Operating System .pptxShell Programming Language in Operating System .pptx
Shell Programming Language in Operating System .pptx
SherinRappai
 

Recently uploaded (20)

PUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for HealthPUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for Health
JonathanHallett4
 
How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18
Celine George
 
How to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo SlidesHow to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo Slides
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-17-2025 .pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-17-2025  .pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-17-2025  .pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-17-2025 .pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdfAntepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Dr H.K. Cheema
 
The History of Kashmir Lohar Dynasty NEP.ppt
The History of Kashmir Lohar Dynasty NEP.pptThe History of Kashmir Lohar Dynasty NEP.ppt
The History of Kashmir Lohar Dynasty NEP.ppt
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdfIPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
Quiz Club of PSG College of Arts & Science
 
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdfGENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
Quiz Club of PSG College of Arts & Science
 
How to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 SalesHow to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 Sales
Celine George
 
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docxPeer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
19lburrell
 
ITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQ
SONU HEETSON
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
PUBH1000 Slides - Module 10: Health Promotion
PUBH1000 Slides - Module 10: Health PromotionPUBH1000 Slides - Module 10: Health Promotion
PUBH1000 Slides - Module 10: Health Promotion
JonathanHallett4
 
MICROBIAL GENETICS -tranformation and tranduction.pdf
MICROBIAL GENETICS -tranformation and tranduction.pdfMICROBIAL GENETICS -tranformation and tranduction.pdf
MICROBIAL GENETICS -tranformation and tranduction.pdf
DHARMENDRA SAHU
 
Launch of The State of Global Teenage Career Preparation - Andreas Schleicher...
Launch of The State of Global Teenage Career Preparation - Andreas Schleicher...Launch of The State of Global Teenage Career Preparation - Andreas Schleicher...
Launch of The State of Global Teenage Career Preparation - Andreas Schleicher...
EduSkills OECD
 
EUPHORIA GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
The Pedagogy We Practice: Best Practices for Critical Instructional Design
The Pedagogy We Practice: Best Practices for Critical Instructional DesignThe Pedagogy We Practice: Best Practices for Critical Instructional Design
The Pedagogy We Practice: Best Practices for Critical Instructional Design
Sean Michael Morris
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
PUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for HealthPUBH1000 Slides - Module 12: Advocacy for Health
PUBH1000 Slides - Module 12: Advocacy for Health
JonathanHallett4
 
How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18
Celine George
 
How to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo SlidesHow to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo Slides
Celine George
 
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdfAntepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Dr H.K. Cheema
 
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales moduleHow To Maximize Sales Performance using Odoo 18 Diverse views in sales module
How To Maximize Sales Performance using Odoo 18 Diverse views in sales module
Celine George
 
How to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 SalesHow to Manage Cross Selling in Odoo 18 Sales
How to Manage Cross Selling in Odoo 18 Sales
Celine George
 
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docxPeer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
Peer Assessment_ Unit 2 Skills Development for Live Performance - for Libby.docx
19lburrell
 
ITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQ
SONU HEETSON
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
PUBH1000 Slides - Module 10: Health Promotion
PUBH1000 Slides - Module 10: Health PromotionPUBH1000 Slides - Module 10: Health Promotion
PUBH1000 Slides - Module 10: Health Promotion
JonathanHallett4
 
MICROBIAL GENETICS -tranformation and tranduction.pdf
MICROBIAL GENETICS -tranformation and tranduction.pdfMICROBIAL GENETICS -tranformation and tranduction.pdf
MICROBIAL GENETICS -tranformation and tranduction.pdf
DHARMENDRA SAHU
 
Launch of The State of Global Teenage Career Preparation - Andreas Schleicher...
Launch of The State of Global Teenage Career Preparation - Andreas Schleicher...Launch of The State of Global Teenage Career Preparation - Andreas Schleicher...
Launch of The State of Global Teenage Career Preparation - Andreas Schleicher...
EduSkills OECD
 
The Pedagogy We Practice: Best Practices for Critical Instructional Design
The Pedagogy We Practice: Best Practices for Critical Instructional DesignThe Pedagogy We Practice: Best Practices for Critical Instructional Design
The Pedagogy We Practice: Best Practices for Critical Instructional Design
Sean Michael Morris
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
Ad

Operating_System_Lab_ClassOperating_System_2.pdf

  • 2. How do you run a shell script from the command line? To run a shell script from the command line, we need to follow these steps: •Make sure the script file has executable permissions using the chmod command: chmod +x myscript.sh •Execute the script using its filename: ./myscript.sh
  • 3. #!/bin/bash #Creates a new variable with a value of "Hello World“ learningbash="Hello World" echo $learningbash The first line (/bin/bash) is used in every bash script. It instructs the operating system to use a bash interpreter as a command interpreter. Hello World is the most simple bash script to start with. We will create a new variable called learningbash and print out the words Hello World. First, open a new shell script file with a text editor of your choice
  • 4. What is the difference between single quotes (‘) and double quotes (“) in shell scripting? Single quotes (‘) and double quotes (“) are used to enclose strings in shell scripting, but they have different behaviors: •Single quotes: Everything between single quotes is treated as a literal string. Variable names and most special characters are not expanded. •Double quotes: Variables and certain special characters within double quotes are expanded. The contents are subject to variable substitution and command substitution. #!/bin/bash abcd=”Hello” echo ‘$abcd’ # Output: $abcd echo “$abcd” # Output: Hello
  • 5. #!/bin/bash #Creates a new variable date=“Monday” echo ‘$date’ echo “$date” echo `date`
  • 6. #!/bin/bash echo "What is your age?" read age echo "Wow, you look younger than $age years old" Get User Input To take input from users, we’ll use the read bash command. First, create a new bash shell file
  • 7. How can you use command-line arguments in a shell script? Command-line arguments are values provided to a script when it’s executed. They can be accessed within the script using special variables like $1, $2, etc., where $1 represents the first argument, $2 represents the second argument, and so on. For Example: If our script name in `example.sh` #!/bin/bash echo “Script name: $0” echo “First argument: $1” echo “Second argument: $2”
  • 8. Conditional Statements The most popular and widely used conditional statement is if. Even though the if statement is easy to write and understand, it can be used in advanced shell scripts as well. #!/bin/bash salary=1000 expenses=800 #Check if salary and expenses are equal if [ $salary == $expenses ] then echo "Salary and expenses are equal" #Check if salary and expenses are not equal elif [ $salary != $expenses ] then echo "Salary and expenses are not equal" fi
  • 9. Check if a Number is Even or Odd Odd and even numbers can be easily divided using the if statement and some simple math. Create a file named evenoddnumbers.sh #!/bin/bash read -p "Enter a number and I will check if its odd or even " mynumber if [ $((mynumber%2)) -eq 0 ] then echo "Your number is even" else echo "Your number is odd." fi
  • 10. #!/bin/bash read -p "Please enter your choice: " response ## If the response given did not consist entirely of digits if [[ ! $response =~ ^[0-9]*$ ]] then ## If it was Quit or quit, exit [[ $response =~ [Qq]uit ]] && exit ## If it wasn't quit or Quit but wasn't a number either, ## print an error message and quit. echo "Please enter a number between 0 and 100 or "quit" to exit" && exit Fi ## Process the other choices if [ $response -le 59 ] then echo "F" elif [ $response -le 69 ] then echo "D" elif [ $response -le 79 ] then echo "C" elif [ $response -le 89 ] Then echo "B" elif [ $response -le 100 ] then echo "A" elif [ $response -gt 100 ] then echo "Please enter a number between 0 and 100" exit fi
  • 11. Loops A loop is an essential tool in various programming languages. To put it simply, a bash loop is a set of instructions that are repeated until a user-specified condition is reached. Start by creating a loop bash program: #!/bin/bash n=0 while : do echo Countdown: $n ((n++)) done This will work as a countdown to infinity until you press CTRL + C to stop the script.
  • 12. #!/bin/bash for (( n=2; n<=10; n++ )) do echo "$n seconds" done
  • 13. Create an Array A bash array is a data structure designed to store information in an indexed way. It is extra useful if users need to store and retrieve thousands of pieces of data fast. What makes bash arrays special is that unlike any other programming language, they can store different types of elements. For example, you can use a bash array to store both strings and numbers. #!/bin/bash # Create an indexed array IndexedArray=(egg burger milk) #Iterate over the array to get all the values for i in "${IndexedArray[@]}";do echo "$i";done
  • 14. Generate Factorial of Number #!/bin/bash echo Enter the number you want to get factorial read mynumber factorial=1 for ((i=1;i<=mynumber;i++)) do factorial=$(($factorial*$i)) done echo $factorial
  • 15. #!/bin/bash echo "Enter a number:" read number i=2 if [ $number -lt 2 ] then echo "$number is not a prime number." exit fi while [ $i -lt $number ] do if [ `expr $number % $i` -eq 0 ] then echo "$number is not a prime number." exit fi i=`expr $i + 1` done echo "$number is a prime number." Shell Script to Check Prime Number #!/bin/bash echo "Enter a number:" read number i=2 if [ $number -lt 2 ] then echo "$number is not a prime number." exit fi max=`echo "sqrt($number)" | bc` while [ $i -le $max ] do if [ `expr $number % $i` -eq 0 ] then echo "$number is not a prime number." exit fi i=`expr $i + 1` done echo "$number is a prime number."
  • 16. #!/bin/bash echo "Enter a number" read num reverse=0 while [ $num -gt 0 ] do remainder=$(( $num % 10 )) reverse=$(( $reverse * 10 + $remainder )) num=$(( $num / 10 )) done echo "Reversed number is : $reverse" Script for reversing a number
  • 17. # Program to print the # given pattern # Static input for N N=5 # variable used for # while loop i=0 j=0 while [ $i -le `expr $N - 1` ] do j=0 while [ $j -le `expr $N - 1` ] do if [ `expr $N - 1` -le `expr $i + $j` ] then # Print the pattern echo -ne "#" else # Print the spaces required echo -ne " " fi j=`expr $j + 1` done # For next line echo i=`expr $i + 1` done Output: # ## ### #### #####
  • 18. Functions A bash function is a set of commands that can be reused numerous times throughout a bash script. #!/bin/bash hello () { echo 'Hello World!’ } hello
  • 19. Display String Length #!/bin/bash # Create a new string mystring="lets count the length of this string" i=${#mystring} echo "Length: $i" Extract String #!/bin/bash cut -d , -f 5 <<< "Website,Domain,DNS,SMTP,5005" #!/bin/bash expr substr "458449Hostinger4132" 7 9 Find and Replace String #!/bin/bash first="I drive a BMW and Volvo" second="Audi" echo "${first/BMW/"$second"}" Concatenate Strings #!/bin/bash firststring="The secret is..." secondstring="Bash" thirdstring="$firststring$secondstring" echo "$thirdstring" #!/bin/bash firststring="The secret is..." firststring+="Bash" echo "$firststring"
  • 20. Read Files #!/bin/bash myvalue=`cat mysamplefile.txt` echo "$myvalue" Print Files With Line Count #!/bin/bash myfile='cars.txt’ i=1 while read lines; do echo "$i : $lines" i=$((i+1)) done < $myfile Delete Files #!/bin/bash myfile='cars.txt’ touch $myfile if [ -f $myfile ]; then rm cars.txt echo "$myfile deleted" fi Test if File Exists #!/bin/bash MyFile=cars.txt if [ -f "$MyFile" ]; then echo "$MyFile exists." else echo "$MyFile does not exist.“ fi
  翻译: