This document provides an overview of Linux Bash shell scripting. It covers topics such as writing basic scripts, variables, conditionals, loops, functions, arguments, and input/output redirection. Examples are given for many common scripting tasks like arithmetic operations, string manipulation, file operations, and comparing values. The document is intended to teach the basics of scripting in the Linux Bash shell.
Getting started with setting up embedded platform requires audience to understand some of the key aspects of Linux. This presentation deals with basics of Linux as an OS, Linux commands, vi editor, Shell features like redirection, pipes and shell scripting
Getting started with setting up embedded platform requires audience to understand some of the key aspects of Linux. This presentation deals with basics of Linux as an OS, Linux commands, vi editor, Shell features like redirection, pipes and shell scripting
Présentation aux Geeks Anonymes Liège par Cyril Soldani, le 13 décembre 2017.
Page des Geeks Anonymes : https://www.recherche.uliege.be/cms/c_9463913/fr/geeks-anonymes
Shell: A Command-Line Interpretor that connects a user to Operating System and allows to execute the commands or by creating text script.
Process: Any task that a user run in the system is called a process. A process is little more complex than just a task.
File: It resides on hard disk (hdd) and contains data owned by a user.
X-windows aka windows: A mode of Linux where screen (monitor) can be split in small “parts” called windows, that allow a user to do several things at the same time and/or switch from one task to another easily and view graphics in a nice way.
Text terminal: A monitor that has only the capability of displaying text stuff, no graphics or a very basic graphics display.
Session: Time between logging on and logging out of the system.
Here, you can learn all information about Shell Script.
1. What is Shell Script?
2. Types of Shell Script.
3. Use of Shell Script.
4. Command line of Shell Script.
5. Example of Shell Script.
Basic of and Unix and Command. More presentation you can find on www.scmGalaxy.com.
scmGalaxy.com is dedicated to software configuration, build and Release management. This covers CVS, VSS (Visual Source Safe),Perforce, SVN(Subversion) MKS Integrity, ClearCase,TFS,CM Synergy, Best Practices ,AnthillPro, Apache Ant, Maven, Bamboo, Cruise Control and many more tools.
A beginners guide to get familiar with the Linux and learn the most commonly and frequently used commands. Most of the commands are expected to run across all well known Linux distributions. Plus, there are a few commands for the advanced users as well.
we need to have a good amount of basic or in-depth knowledge on Linux Basics. This will help one's job easy in resolving the issues and supporting the projects.
Are you a system admin or database admin? Or working on any other technology which is deployed or implemented on linux/UNIX machines? Then you should be good with Linux basic concepts and commands. We will cover this section very clearly.
Useful Linux and Unix commands handbookWave Digitech
This article provides practical examples for most frequently used commands in Linux / UNIX. Helpful for Engineers and trainee engineers, Software developers. A handy notes for all Linux & Unix commands.
Présentation aux Geeks Anonymes Liège par Cyril Soldani, le 13 décembre 2017.
Page des Geeks Anonymes : https://www.recherche.uliege.be/cms/c_9463913/fr/geeks-anonymes
Shell: A Command-Line Interpretor that connects a user to Operating System and allows to execute the commands or by creating text script.
Process: Any task that a user run in the system is called a process. A process is little more complex than just a task.
File: It resides on hard disk (hdd) and contains data owned by a user.
X-windows aka windows: A mode of Linux where screen (monitor) can be split in small “parts” called windows, that allow a user to do several things at the same time and/or switch from one task to another easily and view graphics in a nice way.
Text terminal: A monitor that has only the capability of displaying text stuff, no graphics or a very basic graphics display.
Session: Time between logging on and logging out of the system.
Here, you can learn all information about Shell Script.
1. What is Shell Script?
2. Types of Shell Script.
3. Use of Shell Script.
4. Command line of Shell Script.
5. Example of Shell Script.
Basic of and Unix and Command. More presentation you can find on www.scmGalaxy.com.
scmGalaxy.com is dedicated to software configuration, build and Release management. This covers CVS, VSS (Visual Source Safe),Perforce, SVN(Subversion) MKS Integrity, ClearCase,TFS,CM Synergy, Best Practices ,AnthillPro, Apache Ant, Maven, Bamboo, Cruise Control and many more tools.
A beginners guide to get familiar with the Linux and learn the most commonly and frequently used commands. Most of the commands are expected to run across all well known Linux distributions. Plus, there are a few commands for the advanced users as well.
we need to have a good amount of basic or in-depth knowledge on Linux Basics. This will help one's job easy in resolving the issues and supporting the projects.
Are you a system admin or database admin? Or working on any other technology which is deployed or implemented on linux/UNIX machines? Then you should be good with Linux basic concepts and commands. We will cover this section very clearly.
Useful Linux and Unix commands handbookWave Digitech
This article provides practical examples for most frequently used commands in Linux / UNIX. Helpful for Engineers and trainee engineers, Software developers. A handy notes for all Linux & Unix commands.
Part 5 of "Introduction to Linux for Bioinformatics": Working the command lin...Joachim Jacob
This is part 5 of the training "introduction to linux for bioinformatics". Here we introduce more advanced use on the command line (piping, redirecting) and provide you a selection of GNU text mining and analysis tools that assist you tremendously in handling your bioinformatics data. Interested in following this training session? Contact me at http://www.jakonix.be/contact.html
Asynchronous Web Programming with HTML5 WebSockets and JavaJames Falkner
(Talk originally given @ KCDC - http://kcdc.info ).
Over the last decade, advances in web computing have removed many of the barriers to entry for developers. New languages, frameworks, and development methodologies have kickstarted new ideas and new ways to develop web applications to make modern life easier and more efficient. WebSockets (introduced as part of HTML5) is one such technology that enables a new class of scalable, super-responsive, collaborative, and real-time web applications with a wide range of uses.
In this talk, we will first cover the basics of asynchronous web programming using WebSockets, including predecessors such as polling and long-polling, applications of WebSockets, its limitations and potential bottlenecks, and potential future improvements.
Next, we will demo and dissect a real-world use case for realtime social data analytics, using the Apache Tomcat implementation of WebSockets and the Java-based Liferay Portal Server. This will include a discussion about development of WebSocket endpoints, its lifecycle within the application container and browser, debugging WebSockets, and scalability topics.
Per chi incomincia addentrarsi nel magico mondo dei comandi da terminale la vita può essere dura. In rete esistono diverse guide, ma la “Linux Bash Shell Cheat Sheet for Beginners” di Raphael è qualcosa che i principianti dovrebbero tenere a portata di mano. La segnaliamo un po’ perchè è molto semplice e chiara, e un po’ perchè è stata scritta da un sedicenne canadese. Personalmente è una cosa che mi fa piacere, perchè dimostra che anche i giovanissimi si accostano a linux nel modo migliore, ovvero “imparo e a mia volta diffondo”.
Serverless Data Architecture at scale on Google Cloud Platform - Lorenzo Ridi...Codemotion
Let's say you are in charge of the design of a data processing architecture. You finally managed to deploy and tune the "ideal" configuration, but data are like weeds: they just KEEP GROWING! So, eventually you have to add new pieces, or even start over and re-design everything. Sounds familiar? Cloud can be a solution to this Data Architect nightmare. In this talk we will build an end-to-end Serverless, No-Ops, scalable and reliable data solution, based on Google Cloud Platform.
What is Apache Mesos and how to use it. A short introduction to distributed fault-tolerant systems with using ZooKeeper and Mesos. #installfest Prague 2014
Whether you call yourself a system administrator, developer, or DevOps sprint mediator, life is too short for sloppy shell scripts! In this talk, we look at how to improve them to stand the test of time. Michael will share how to create a good foundation for your scripts, so they run more reliable now and in the future. Your (future) colleagues might love you for it.
Focus areas of this presentation include error handling, security, style, and best practices. Also, it will cover (many) mistakes made by Michael over the last 20 years.
The Korn Shell is the UNIX shell (command execution program, often c.docxSUBHI7
The Korn Shell is the UNIX shell (command execution program, often called a command interpreter) that was developed by David Korn of Bell Labs as a comprehensive, combined version of other major UNIX shells. Incorporating all the features of the C shell (csh) and the Tab C-shell (tcsh) with the script language features similar to that of the Bourne Shell, the Korn Shell is considered the most efficient shell. Korn, Bourne, and C are the 3 most commonly used UNIX shells. You will be using the Korn Shell (ksh) for this project in which you will be writing shell script files.
1.
Begin by executing the following command from a terminal session in your Ubuntu system:
sudo apt-get install ksh
You will immediately be asked to enter your password (csci345). This will install the Korn shell into your Ubuntu system on your PC or Mac for use in this project. Simply type
ksh
and to go into the Korn Shell (your system prompt will change to $ only) and then enter CTRL-D to exit out of it (your default system prompt of
[email protected]
:~$ will re-appear).
As you go through this exercise and start writing shell scripts, you will learn some additional troubleshooting tips to help you navigate through the Korn Shell (ksh).
Keep track of some of these tips (5 of them) and put them into a Word document in a list format with explanations (at least 150 words in current APA format). Make sure that these are different from those mentioned in the textbook.
2.
Do some research on what the Korn Shell is about and what it has to offer. Provide some basic information (3–5 key points) in a short report (at least 150 words in current APA format) and compile it into the same Word document as above and submit it with this project. Also, provide 5–7 positive features of the Korn Shell (ksh) in the same report (at least 150 words in current APA format) in a list. Below are 3 websites that can assist you in this effort. You will need at least 2 external references for this short report (in addition to your textbook):
-
http://kornshell.com/
-
http://www.dartmouth.edu/~rc/classes/ksh/print_pages.shtml
-
http://www.bolthole.com/solaris/ksh.html
There are many other websites out there that will give you additional help, if needed. Take a look at the ksh shell script below. There are 3 versions of essentially the same program, which is a wrapper to edit a file under SCCS version control. The basic task is to use the sccs command to “check out” a file under version control and then automatically edit the file. The script will then be used by users who may not be particularly advanced UNIX users. Hence, the need for a wrapper script. While the basic functionality is the same across all versions, the differences in safety and usability between the first version and the last (4th) version are worth noting. The first one is extremely bad: it would be written by someone who has just picked up a book on shell scripting and has decided, “I’m a programmer.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
2. • A script is a list of system commands stored in a
file.
• Steps to write a script :-
• Use any editor like vi or vim
• chmod permission your-script-name.
• Examples:-
•
$ chmod +x <filename.sh>
•
$ chmod 755 <filename.sh>
• Execute your script as:
• $ bash filename.sh
• $ bash fileneme.sh
• $ ./filename.sh
4/29/2014 Linux Bash Shell script 2
3. • My first shell script
clear
• echo “hello world“
• $ ./first
• $ chmod 755 first
• $ ./first
• Variables in Shell:
• In Linux (Shell), there are two types of variable:
• (1) System variables :
• (2) User defined variables :
4/29/2014 Linux Bash Shell script 3
4. • $ echo $USERNAME
• $ echo $HOME
• User defined variables :
• variable name=value
• Examples:
• $x = 10
• echo Command:
• echo command to display text
4/29/2014 Linux Bash Shell script 4
7. processes
• $ ps
PID TTY TIME CMD
• $ ps -ef
UID PID PPID C STIME TTY TIME CMD
• $ ps -l
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME
CMD
• $ ps -efH
UID PID PPID C STIME TTY TIME CMD
4/29/2014 Linux Bash Shell script 7
8. Creating files:
$ touch test1
$ ls -il test1
Copying files:
cp source destination
cp test1 test2
Linking files:
There are two different types of file links in Linux:
a. A symbolic, or soft, link
b. A hard link
4/29/2014 Linux Bash Shell script 8
9. Quotes
" Double
Quotes
Double Quotes" -
Anything enclose in
double quotes removed
meaning of that
characters (except
and $).
' Single quotes 'Single quotes' - Enclosed in
single quotes remains
unchanged.
` Back quote `Back quote` - To execute
command
4/29/2014 Linux Bash Shell script 9
10. • Pipes:
who | wc –l
Reading from Files:
$ read message
$ echo $message
Read command to read lines from files
• Command substitution:
Var=`date`
Var=$(date)
• Background Processes:
• ls -R /tmp &
4/29/2014 Linux Bash Shell script 10
11. Reading with While
while read ip name alias
do
if [ ! -z “$name” ]; then
# Use echo -en here to suppress ending the line;
# aliases may still be added
echo -en “IP is $ip - its name is $name”
if [ ! -z “$aliases” ]; then
echo “ Aliases: $aliases”
else
# Just echo a blank line
echo
fi
fi
done < /etc/hosts
4/29/2014 Linux Bash Shell script 11
12. Stopping processes
kill pid
disk space
$ df
$ df –h
Disk usages:
$ du
Commands:
$ cat file1
$ sort file1
$ cat file2
$ sort file2
$ sort -n file2
4/29/2014 Linux Bash Shell script 12
13. Searching for data
• grep [options] pattern [file]
• The grep command searches either the input
or the file you specify for lines that contain
characters that match the specified pattern.
The output from grep is the lines that contain
the matching pattern.
4/29/2014 Linux Bash Shell script 13
14. RANDOM produces a random number between 0 and 32767.
This simple recipe produces 10 random
numbers between 200 and 500:
$ cat random.sh
#!/bin/bash
MIN=200
MAX=500
let “scope = $MAX - $MIN”
if [ “$scope” -le “0” ]; then
echo “Error - MAX is less than MIN!”
fi
for i in `seq 1 10`
do
let result=”$RANDOM % $scope + $MIN”
echo “A random number between $MIN and $MAX is $result”
Done
$ ./random.sh
4/29/2014 Linux Bash Shell script 14
15. Problem 1: Code to calculate the length of the hypotenuse of
a Pythagorean triangle
$ cat hypotenuse.sh
#!/bin/sh
# calculate the length of the hypotenuse of a Pythagorean
triangle
# using hypotenuse^2 = adjacent^2 + opposite^2
echo -n “Enter the Adjacent length: “
read adjacent
echo -n “Enter the Opposite length: “
read opposite
osquared=$(($opposite ** 2)) # get o^2
asquared=$(($adjacent ** 2)) # get a^2
hsquared=$(($osquered + $asquared)) # h^2 = a^2 + o^2
hypotenuse=`echo “scale=3;sqrt ($hsquared)” | bc`
# bc does sqrt
echo “The Hypotenuse is $hypotenuse”
4/29/2014 Linux Bash Shell script 15
16. Environment Variables
• There are two types of environment variables in the
bash shell
• Global variables
• Local variables
4/29/2014 Linux Bash Shell script 16
17. Variable Arrays
• An array is a variable that can hold multiple values.
• To set multiple values for an environment variable, just list
them in parentheses, with each value
• separated by a space:
• $ mytest=(one two three four five)
• $
• Not much excitement there. If you try to display the array
as a normal environment variable,
• you’ll be disappointed:
• $ echo $mytest
• one
• $
• Only the first value in the array appears. To reference an
individual array element, you must use
• a numerical index value, which represents its place in the
array. The numeric value is enclosed in
• square brackets:
• $ echo ${mytest[2]}
• three
• $
4/29/2014 Linux Bash Shell script 17
18. Scripting basics
$ date ; who
$ chmod u+x test1
$ ./test1
$ echo This is a test
This is a test
$ echo Let’s see if this’ll work
Lets see if thisll work
$
4/29/2014 Linux Bash Shell script 18
19. The backtick
One of the most useful features of shell scripts is the lowly
back quote character, usually called the
backtick (`) in the Linux world.
You must surround the entire command line command with
backtick characters:
testing=`date`
$ cat test5
#!/bin/bash
# using the backtick character
testing=`date`
echo "The date and time are: " $testing
$
4/29/2014 Linux Bash Shell script 19
20. Redirecting Input and Output
• Output redirection
The most basic type of redirection is sending output from a
command to a file. The bash shell uses the greater-than
symbol for this:
command > outputfile
Input redirection
Input redirection is the opposite of output redirection
The input redirection symbol is the less-than symbol (<):
command < inputfile
4/29/2014 Linux Bash Shell script 20
21. The expr command
$ expr 1 + 5
6
The bash shell includes the expr command to stay compatible
with the Bourne shell; however, it
also provides a much easier way of performing mathematical
equations
$ var1=$[1 + 5]
$ echo $var1
6
$ var2 = $[$var1 * 2]
$ echo $var2
12
$
4/29/2014 Linux Bash Shell script 21
22. $ chmod u+x test7
$ ./test7
The final result is 500
$
Using bc in scripts
variable=`echo "options; expression" | bc`
$ chmod u+x test9
$ ./test9
The answer is .6880
$
$ cat test10
#!/bin/bash
var1=100
4/29/2014 Linux Bash Shell script 22
23. var2=45
var3=`echo "scale=4; $var1 / $var2" | bc`
echo The answer for this is $var3
$
$ cat test11
#!/bin/bash
var1=20
var2=3.14159
var3=`echo "scale=4; $var1 * $var1" | bc`
var4=`echo "scale=4; $var3 * $var2" | bc`
echo The final result is $var4
$
4/29/2014 Linux Bash Shell script 23
27. Structured Commands
• if-then Statement:
The if-then statement has the following format:
if command
then
commands
Fi
The if-then-else Statement
if command
then
commands
else
commands
fi
4/29/2014 Linux Bash Shell script 27
28. Nesting ifs
if command1
then
commands
elif command2
then
more commands
Fi
• You can continue to string elif statements together, creating one huge if-
then-elif conglomeration:
if command1
then
command set 1
elif command2
then
command set 2
elif command3
then
command set 3
elif command4
then
command set 4
fi
4/29/2014 Linux Bash Shell script 28
29. Numeric comparisons
• The most common method for using the test command is
to perform a comparison of two numeric values.
#!/bin/bash
# using numeric test comparisons
val1=10
val2=11
if [ $val1 -gt 5 ]
then
echo "The test value $val1 is greater than 5"
fi
if [ $val1 -eq $val2 ]
then
echo "The values are equal"
else
echo "The values are different"
fi
4/29/2014 Linux Bash Shell script 29
30. Comparison Description
n1 -eq n2 Check if n1 is equal to n2.
n1 -ge n2 Check if n1 is greater than or equal to
n2.
n1 -gt n2 Check if n1 is greater than n2.
n1 -le n2 Check if n1 is less than or equal to
n2.
n1 -lt n2 Check if n1 is less than n2.
4/29/2014 Linux Bash Shell script 30
31. String comparisons
• String equality
• The equal and not equal conditions are fairly self-
explanatory with strings. It’s pretty easy to know
• when two string values are the same or not:
#!/bin/bash
# testing string equality
testuser=rich
if [ $USER = $testuser ]
then
echo "Welcome $testuser"
fi
$ ./test7
Welcome rich
$
4/29/2014 Linux Bash Shell script 31
32. The test Command String Comparisons
Comparison Description
str1 = str2 Check if str1 is the same as
string str2.
str1 != str2 Check if str1 is not the same as
str2.
str1 < str2 Check if str1 is less than str2.
str1 > str2 Check if str1 is greater than
str2.
4/29/2014 Linux Bash Shell script 32
33. The for Command
for var in list
do
commands
Done
Reading values in a list
#!/bin/bash
# basic for command
for test in Alabama Alaska Arizona Arkansas California Colorado
do
echo The next state is $test
done
$ ./test1
4/29/2014 Linux Bash Shell script 33
34. reading values from a file
file="states"
for state in `cat $file`
do
echo "Visit beautiful $state"
Done
4/29/2014 Linux Bash Shell script 34
35. internal field separator
A space
A tab
A newline
file="states"
IFS=$’n’
for state in `cat $file`
do
echo "Visit beautiful $state"
Done
4/29/2014 Linux Bash Shell script 35
36. Reading a directory using wildcards
for file in /home/tmp/*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif [ -f "$file" ]
Then
echo "$file is a file"
fi
Done
4/29/2014 Linux Bash Shell script 36
37. For loop
for (( i=1; i ‹= 10; i++ ))
do
echo "The next number is $i"
done
4/29/2014 Linux Bash Shell script 37
38. Multi.sh
#!/bin/sh
a=$1
if [ $a -lt 1 -o $a -gt 9 ]; then
echo “The number is out of range [1,9]”
exit
fi
echo "Multiplication Table for $a"
for i in 1 2 3 4 5 6 7 8 9
do
m=$[a * i]
echo "$a x $i = $m"
done
4/29/2014 Linux Bash Shell script 38
39. Shell Arguments
#!/bin/sh
echo "Total number of arguments = $#"
echo "Shell script name = $0"
echo "First arguemnt = $1"
echo "Second arguemnt = $2"
echo “Third argument = $3”
echo "All arguments (a word) = $*"
echo "All arguments in array = $@"
4/29/2014 Linux Bash Shell script 39
40. Loops
#!/bin/sh
for i in 1 2 3 4 5 6 7 8 9
do
echo “number $i”
done
#!/bin/sh
for i in `seq 1 100`
do
if [ $i -lt 5 ]; then
continue
elif [ $i -gt 10 ]; then
break
fi
echo "number $i"
done
4/29/2014 Linux Bash Shell script 40
42. multiple variables
for (( a=1, b=10; a ‹= 10; a++, b-- ))
do
echo "$a - $b"
Done
Nesting Loops:
for (( a = 1; a ‹= 3; a++ ))
do
echo "Starting loop $a:"
for (( b = 1; b ‹= 3; b++ ))
do
echo " Inside loop: $b"
done
done
4/29/2014 Linux Bash Shell script 42
44. Breaking out of an inner loop
for (( a = 1; a ‹ 4; a++ ))
do
echo "Outer loop: $a"
for (( b = 1; b ‹ 100; b++ ))
do
if [ $b -eq 5 ]
then
break
fi
echo " Inner loop: $b"
done
done
4/29/2014 Linux Bash Shell script 44
45. Breaking out of an outer loop
for (( a = 1; a ‹ 4; a++ ))
do
echo "Outer loop: $a"
for (( b = 1; b ‹ 100; b++ ))
do
if [ $b -gt 4 ]
then
break 2
fi
echo " Inner loop: $b"
done
done
4/29/2014 Linux Bash Shell script 45
46. The continue command
for (( var1 = 1; var1 ‹ 15; var1++ ))
do
if [ $var1 -gt 5 ] && [ $var1 -lt 10 ]
then
continue
fi
echo "Iteration number: $var1"
done
4/29/2014 Linux Bash Shell script 46
47. Continue
for (( a = 1; a ‹= 5; a++ ))
do
echo "Iteration $a:"
for (( b = 1; b ‹ 3; b++ ))
do
if [ $a -gt 2 ] && [ $a -lt 4 ]
then
continue 2
fi
var3=$[ $a * $b ]
echo " The result of $a * $b is $var3"
done
done
4/29/2014 Linux Bash Shell script 47
48. Read file into bash array
– exec < $1
let count=0
while read LINE; do
ARRAY[$count]=$LINE
((count++))
done
echo Number of elements: ${#ARRAY[@]}
# echo array's content
echo ${ARRAY[@]}
# restore stdin from filedescriptor 10
# and close filedescriptor 10
exec 0<&10 10<&-
4/29/2014 Linux Bash Shell script 48
49. Processing the Output of a
Loop
for file in /home/rich/*
do
if [ -d "$file" ]
then
echo "$file is a directory"
elif
echo "$file is a file"
fi
done > output.txt
4/29/2014 Linux Bash Shell script 49
51. Using functions
function func1 {
echo "This is an example of a
function"
}
count=1
while [ $count -le 5 ]
do
func1
count=$[ $count + 1 ]
done
4/29/2014 Linux Bash Shell script 51
52. 4/29/2014 Linux Bash Shell script 52
count=1
echo "This line comes before the function
definition"
function func1 {
echo "This is an example of a function"
}
while [ $count -le 5 ]
do
func1
count=$[ $count + 1 ]
done
echo "This is the end of the loop"
func2
echo "Now this is the end of the script"
function func2 {
echo "This is an example of a function"
}
53. Regex
• $echo {a..z}
• $ echo {5..-1}
• if [[ $digit =~ [0-9] ]]; then echo
'$digit is a digit' else echo "oops" fi
4/29/2014 Linux Bash Shell script 53
54. Regular expression operators
Operator
. Matches any single character.
? The preceding item is optional
and will be matched, at most,
once.
* The preceding item will be
matched zero or more times.
+ The preceding item will be
matched one or more times.
{N} The preceding item is matched
exactly N times.
{N,} The preceding item is matched N
or more times.
{N,M} The preceding item is matched at
least N times, but not more than
M times.
4/29/2014 Linux Bash Shell script 54
55. Regular expressions
As with other comparison operators (e.g., -lt or ==), bash will
return a zero if an expression like $digit =~ "[[0-9]]"
shows that the variable on the left matches the expression
on the right and a one otherwise. This example test asks
whether the value of $digit matches a single digit.
if [[ $digit =~ [0-9] ]]; then
echo '$digit is a digit'
else
echo "oops"
fi
You can also check whether a reply to a prompt is
numeric with similar syntax:
echo -n "Your answer> "
read REPLY
if [[ $REPLY =~ ^[0-9]+$ ]]; then
echo Numeric
else
echo Non-numeric
fi
4/29/2014 Linux Bash Shell script 55
56. Sample bash script to perform the unpack/compile process
#!/usr/bin/env bash
if [ -d work ]
then
# remove old work directory if it exists
rm -rf work
fi
mkdir work
cd work
tar xzf /usr/src/distfiles/sed-3.02.tar.gz
cd sed-3.02
./configure --prefix=/usr
make
4/29/2014 Linux Bash Shell script 56