SlideShare a Scribd company logo
LINUX SYSTEM
ADMINISTRATION
UNIT 5. CHP 1. Introducing
Bash
Shell Scripting
MR JAYANT PRADEEP DALVI
INTRODUCTION
• A shell script is a text file that contains a sequence of commands
Elements of a Good Shell Script
When writing a script, make sure it meets the following recommendations:
• Has a unique name
• Includes the shebang (#!) to tell the shell which subshell should execute
the script
• Includes comments—lots of comments
• Uses the exit command to tell the shell executing the script that it has
executed successfully
• Is executable.
Creating Your First Shell Script
We can type following code, and save it with the name hello in your
home directory.
#!/bin/bash
# this is the hello script
# run it by typing ./hello in the directory where you've found it
clear
echo hello world //print the output
exit 0
• In the first line of the script, you can find the shebang. This scripting
element tells the shell executing this script which subshell should
execute this script.
• The shebang always starts with #! and is followed by the name of the
subshell that should execute the script. In our previous example we
used /bin/bash as the subshell, but you can use any other shell you like.
For instance, use #!/bin/perl if your script contains Perl code.
• The second part in the script in our example consists of two lines of
comments. As you can see, these comment lines explain to the user
the purpose of the script and how to use it.
• The command exit 0 is used as the last part of the script. It is good
habit to use the exit command in all of your scripts. This command
exits the script and then tells the parent shell how the script has
executed.
Executing the Script
Now that you have written your first shell script, it’s time to execute it.
There are three different ways of doing this.
1. Make it executable, and run it as a program.
2. Run it as an argument of the bash command.
3. Source it.
Making the Script Executable
• The most common way to run a shell script is by making it executable.
To do this with the hello script from our example,we use the following
command: chmod +x hello
• After making the script executable, you can run it just like any other
command.
• If user linda created a script with the name hello in /home/linda, she
has to run it using the command /home/linda/hello. Alternatively, if she
is already in /home/linda, she could use ./hello to run the script.
• In the latter example, the dot and slash tell the shell to run the
command from the current directory.
Running the Script as an Argument of the Bash
Command
• The second option for running a script is to specify its name as the
argument of the bash command. For example, the script hello would
run using the command bash hello.
• The advantage of running the script this way is that there is no need
to make it executable first.
• If the script is /home/linda/hello and your current directory is /tmp, you
should run it using bash /home/linda/hello.
Working with Variables and Input
• A variable is a value you get from somewhere that will be dynamic.
The value of a variable normally depends on the circumstances.
• For example, you can have your script get the variable itself by
executing a command, making a calculation, specifying it as a
command-line argument for the script, or modifying a text string.
Understanding Variables
• You can define a variable somewhere in a script and use it in a flexible
way later. You can also define a variable in a shell. To define a variable,
use varname=value to get the value of a variable. Later, you can call its
value using the echo command.
• We will see an example of how a variable is set on the command line
and how its value is used in the next command.
Setting and using a variable
nuuk:~ # HAPPY=yes
nuuk:~ # echo $HAPPY
yes
Variables, Subshells, and Sourcing
• When defining variables, we have to check a variable is defined for
the current shell only. This means that if you start a subshell from the
current shell, the variable will not be there.
• Moreover, if you define a variable in a subshell, it won’t be there
anymore once you’ve quit the subshell and returned to the parent
shell.
•Variables are local to the shell where they are defined
nuuk:~/bin # HAPPY=yes
nuuk:~/bin # echo $HAPPY
yes
nuuk:~/bin # bash //subshell=bash
nuuk:~/bin # echo $HAPPY
nuuk:~/bin # exit
exit
nuuk:~/bin # echo $HAPPY
yes
nuuk:~/bin #
• In above example, we have defined a variable with the name HAPPY.
You can then see that its value is correctly echoed.
• In the third command, a subshell is started, and as you can see, when
asking for the value of the variable HAPPY in this subshell, it isn’t there
because it simply doesn’t exist.
• But when the subshell is closed using the exit command, you’re back
in the parent shell where the variable still exists.
• In some cases, you may want to set a variable that is present in all
subshells as well.
• If this is the case, you can define it using the export command. For
example, the command export HAPPY=yes defines the variable HAPPY
and makes sure that it is available in all subshells from the current
shell forward until the computer is rebooted.
• However, there is no way to define a variable and make it available in
the parent shells in this manner.
•By exporting a variable, you can also make it available in
subshells
nuuk:~/bin # export HAPPY=yes
nuuk:~/bin # echo $HAPPY
yes
nuuk:~/bin # bash
nuuk:~/bin # echo $HAPPY
yes
nuuk:~/bin # exit
exit
nuuk:~/bin # echo $HAPPY
yes
nuuk:~/bin #
•By putting all your variables in one file, you can make them easily
available
HAPPY=yes
ANGRY=no
SUNNY=yes
•The main advantage of putting all variables in one file is that you can
also make them available in other shells by sourcing them.
•Example of sourcing usage
nuuk:~/bin # echo $HAPPY
nuuk:~/bin # echo $ANGRY
nuuk:~/bin # echo $SUNNY
nuuk:~/bin # . vars
nuuk:~/bin # echo $HAPPY
yes
nuuk:~/bin # echo $ANGRY
no
nuuk:~/bin # echo $SUNNY
yes
nuuk:~/bin #
Working with Script Arguments
• Till now we learned how to define variables and how to create a
variable in a static way. Here we will learn how to provide values for
your variables dynamically by specifying them as an argument for the
script when running it on the command line.
Using Script Arguments
• When running a script, you can specify arguments to the script on the
command line.
• Consider the script dirscript from Example 1. You could run it with an
argument on the command line like this: dirscript /blah.
•You can refer to the first argument used in the script as $1 in the script,
the second argument as $2, and so on, up to $9. You can also use $0 to
refer to the name of the script itself.
#!/bin/bash
#
# argscript
#
# Silly script that shows how arguments are used
ARG1=$1
ARG2=$2
ARG3=$3
SCRIPTNAME=$0
echo The name of this script is $SCRIPTNAME
echo The first argument used is $ARG1
echo The second argument used is $ARG2
echo The third argument used is $ARG3
exit 0
Example 1:
#!/bin/bash
#
# dirscript
#
# Silly script that creates a directory with a certain name
# next sets $USER and $GROUP as the owners of the directory
# and finally changes the permission mode to 770
# Provide the directory name first, followed by the username and
# finally the groupname.
DIRECTORY=$1
USER=$2
GROUP=$3
mkdir /$DIRECTORY
chown $USER $DIRECTORY
chgrp $GROUP $DIRECTORY
chmod 770 $DIRECTORY
exit 0
Counting the Number of Script Arguments
Occasionally, you’ll want to check the number of arguments provided
with a script. This is useful if you expect a certain number of arguments
and want to make sure that this number is present before running the
script.
To count the number of arguments provided with a script, you can use
$#. Basically, $# is a counter that just shows you the exact number of
arguments used when running a script. For example, you could use it to
show a help message if the user hasn’t provided the correct number of
arguments. In Exercise 2, the script countargs does this using $#. There is
a sample running of the script directly after the code listing.
RUN FOLLOWING SCRIPTS
#!/bin/bash
#
# countargs
# sample script that shows how many
arguments were used
echo the number of arguments is $#
exit 0
nuuk:~/bin # ./countargs a b c d e
the number of arguments is 5
nuuk:~/bin #.
Asking for Input
• Another way to get input is simply to ask for it. To do this, you can use
read in the script.
• When using read, the script waits for user input and puts that into a
variable. In Exercise 3, you will create a simple script that first asks for
input and then reflects the input provided by echoing the value of the
variable.
#!/bin/bash
#
# askinput
# ask user to enter some text and then display it
echo Enter some text
read SOMETEXT
echo -e "You have entered the following text:t $SOMETEXT"
exit 0
Using Command Substitution
• Another way of putting a variable text in a script is by using command
substitution. In command substitution, you use the result of a command
in the script. This is useful if the script has something to do with the
result of a command. For example, you can use this technique to tell a
script that it should execute only if a certain condition is met (using a
conditional loop with if to accomplish this).
• To use command substitution, put the command that you want to use
between backquotes (also known as back ticks).
• As an alternative, you can put the command substitution between
braces with a $ sign in front of the (.
•The following sample code shows how this works:
nuuk:~/bin # echo "today is $(date +%d-%m-%y)" $()
today is 04-06-12
•In this example, the date command is used with some of its special
formatting characters.
•The command date +%d-%m-%y tells date to present its result in the day-
month-year format.
•However, you can also put the result of the command substitution in a
variable, which makes it easier to perform a calculation on the result
later in the script. The following sample code shows how to do that:
nuuk:~/bin # TODAY=$(date +%d-%m-%y)
nuuk:~/bin # echo today=$TODAY
today is 27-01-09
Substitution Operators
• It may be important to verify that a variable indeed has a value
assigned to it within a script before the script continues. To do this,
bash offers substitution operators.
• Substitution operators let you assign a default value if a variable
doesn’t have a currently assigned value and much more.
sander@linux %> echo $BLAH
sander@linux %> echo ${BLAH:-variable is empty}
variable is empty
sander@linux %> echo $BLAH
sander@linux %> echo ${BLAH=value}
value
sander@linux %> echo $BLAH
value
sander@linux %> BLAH
sander@linux %> echo ${BLAH=value}
sander@linux %> echo ${BLAH:=value}
value
sander@linux %> echo $BLAH
value
sander@linux %> echo ${BLAH:+sometext}
sometext
Changing Variable Content with Pattern
Matching
• You’ve just seen how substitution operators can be used to supply a
value to a variable that does not have one. A pattern-matching operator
can be used to search for a pattern in a variable and, if that pattern is
found, modify the variable. This is very useful because it allows you to
define a variable in exactly the way you want.
• For example, think of the situation in which a user enters a complete
path name of a file but only the name of the file (without the path) is
needed in your script.
• You can use the pattern-matching operator to change this. Pattern-
matching operators allow you to remove part of a variable automatically.
#!/bin/bash
# stripit
# script that extracts the file name from a filename that includes the
path
# usage: stripit <complete file name>
filename=${1##*/}
echo "The name of the file is $filename"
exit 0
Performing Calculations
bash offers some options that allow you to perform calculations from
scripts.
For example, you can use bash calculation options to execute a
command a number of times or to make sure that a counter is
incremented when a command executes successfully.
•Using a counter in a script
#!/bin/bash
# counter
# script that counts until infinity
counter=1
counter=$((counter + 1))
echo counter is set to $counter
exit 0
Using Control Structures
bash offers many options to use flow control in scripts.
•if: Use if to execute commands only if certain conditions are met.
•To customize the working of if further, you can use else to indicate what
should happen if the condition isn’t met.
•case: Use case to handle options. This allows the user to specify further
the working of the command as it is run.
•for This construction is used to run a command for a given number of
items. For example, you can use for to do something for every fi le in a
specified directory.
•while: Use while as long as the specified condition is met. For example,
this construction can be very useful to check whether a certain host is
reachable or to monitor the activity of a process.
•until: This is the opposite of while. Use until to run a command until a
certain condition
test command: This command is used to perform many checks to see,
Using if...then...else
•The basic construction is if condition then command fi. Therefore, you’ll
use it to check one specific condition, and if it is true, a command is
executed
#!/bin/bash
# testarg
# test to see if argument is present
if [ -z $1 ]
then
echo You have to provide an argument with this command
exit 1
fi
echo the argument is $1
exit 0
•Nesting if control structures
#!/bin/bash
# testfile
if [ -f $1 ]
then
echo "$1 is a file"
elif [ -d $1 ]
then
echo "$1 is a directory"
else
echo "I don't know what $1 is"
fi
exit 0
Using case
•Write a script that advises the user about the capabilities of their
favorite soccer team. The script should contain the following
components:
1. It should ask the user to enter the name of a country.
2. It should use case to test against different country names.
3. It should translate all input to uppercase to make evaluation of the
user input easier.
4. It should tell the user what kind of input is expected
#!/bin/bash
# soccer
# Your personal soccer expert
# predicts world championship
football
cat << EOF
read COUNTRY
# tranlate $COUNTRY into all
uppercase
COUNTRY=`echo $COUNTRY | tr
a-z A-Z`
case $COUNTRY in
NEDERLAND | HOLLAND | NETHERLANDS)
echo "Yes, you are a soccer expert "
;;
DEUTSCHLAND | GERMANY | MANNSCHAFT)
echo "No, they are the worst team on earth"
;;
ENGLAND | AUSTRALIA | FRANCE | BRAZIL)
echo "hahahahahahaha, you must be joking"
;;
*)
echo "Huh? Do they play soccer?"
;;
esac
exit 0
Using while
•You can use while to run a command as long as a condition is met.
Using until
•Whereas while works as long as a certain condition is met, until is just
the opposite; that is, it runs until the condition is met.
#!/bin/bash
# usermon
# script that alerts when a user logs in
# usage: ishere <username>
until who | grep $1 >> /dev/null
do
echo $1 is not logged in yet
sleep 5
done
echo $1 has just logged in
exit 0
Using for
•Sometimes it’s necessary to execute a series of commands, either for a
limited number of times or for an unlimited number of times. In such
cases, for loops offer an excellent solution.
#!/bin/bash
# counter
# counter that counts from 1 to 9
for (( counter=1; counter<10; counter++ )); do
echo "The counter is now set to $counter"
done
exit 0

More Related Content

What's hot

Unix shell scripts
Unix shell scriptsUnix shell scripts
Unix shell scripts
Prakash Lambha
 
UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2
Nihar Ranjan Paital
 
UNIX - Class4 - Advance Shell Scripting-P1
UNIX - Class4 - Advance Shell Scripting-P1UNIX - Class4 - Advance Shell Scripting-P1
UNIX - Class4 - Advance Shell Scripting-P1
Nihar Ranjan Paital
 
Bash shell
Bash shellBash shell
Bash shellxylas121
 
Cleancode
CleancodeCleancode
Cleancode
hendrikvb
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 
Beautiful Bash: Let's make reading and writing bash scripts fun again!
Beautiful Bash: Let's make reading and writing bash scripts fun again!Beautiful Bash: Let's make reading and writing bash scripts fun again!
Beautiful Bash: Let's make reading and writing bash scripts fun again!
Aaron Zauner
 
2-introduction_to_shell_scripting
2-introduction_to_shell_scripting2-introduction_to_shell_scripting
2-introduction_to_shell_scriptingerbipulkumar
 
Shell programming 1.ppt
Shell programming  1.pptShell programming  1.ppt
Shell programming 1.ppt
Kalkey
 
UNIX - Class1 - Basic Shell
UNIX - Class1 - Basic ShellUNIX - Class1 - Basic Shell
UNIX - Class1 - Basic Shell
Nihar Ranjan Paital
 
Easiest way to start with Shell scripting
Easiest way to start with Shell scriptingEasiest way to start with Shell scripting
Easiest way to start with Shell scripting
Akshay Siwal
 
Shell Script Linux
Shell Script LinuxShell Script Linux
Shell Script Linux
Wellington Oliveira
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)jewelyngrace
 
Exploring Code with Pry!
Exploring Code with Pry!Exploring Code with Pry!
Exploring Code with Pry!
Clayton Parker
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell ScriptingRaghu nath
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Manav Prasad
 

What's hot (20)

Unix shell scripts
Unix shell scriptsUnix shell scripts
Unix shell scripts
 
UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2UNIX - Class5 - Advance Shell Scripting-P2
UNIX - Class5 - Advance Shell Scripting-P2
 
UNIX - Class4 - Advance Shell Scripting-P1
UNIX - Class4 - Advance Shell Scripting-P1UNIX - Class4 - Advance Shell Scripting-P1
UNIX - Class4 - Advance Shell Scripting-P1
 
Bash shell
Bash shellBash shell
Bash shell
 
Cleancode
CleancodeCleancode
Cleancode
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
Beautiful Bash: Let's make reading and writing bash scripts fun again!
Beautiful Bash: Let's make reading and writing bash scripts fun again!Beautiful Bash: Let's make reading and writing bash scripts fun again!
Beautiful Bash: Let's make reading and writing bash scripts fun again!
 
2-introduction_to_shell_scripting
2-introduction_to_shell_scripting2-introduction_to_shell_scripting
2-introduction_to_shell_scripting
 
Shell programming 1.ppt
Shell programming  1.pptShell programming  1.ppt
Shell programming 1.ppt
 
UNIX - Class1 - Basic Shell
UNIX - Class1 - Basic ShellUNIX - Class1 - Basic Shell
UNIX - Class1 - Basic Shell
 
Easiest way to start with Shell scripting
Easiest way to start with Shell scriptingEasiest way to start with Shell scripting
Easiest way to start with Shell scripting
 
Shell Script Linux
Shell Script LinuxShell Script Linux
Shell Script Linux
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)
 
003 scripting
003 scripting003 scripting
003 scripting
 
Slides
SlidesSlides
Slides
 
perltut
perltutperltut
perltut
 
Exploring Code with Pry!
Exploring Code with Pry!Exploring Code with Pry!
Exploring Code with Pry!
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Chap06
Chap06Chap06
Chap06
 

Similar to Linux System Administration

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_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdfShell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdf
HIMANKMISHRA2
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
mugeshmsd5
 
Case, Loop & Command line args un Unix
Case, Loop & Command line args un UnixCase, Loop & Command line args un Unix
Case, Loop & Command line args un Unix
Vpmv
 
Licão 05 scripts exemple
Licão 05 scripts exempleLicão 05 scripts exemple
Licão 05 scripts exemple
Acácio Oliveira
 
Shell programming
Shell programmingShell programming
Shell programming
Moayad Moawiah
 
Variables and User Input
Variables and User InputVariables and User Input
Variables and User Input
primeteacher32
 
Unix shell scripting tutorial
Unix shell scripting tutorialUnix shell scripting tutorial
Unix shell scripting tutorial
Prof. Dr. K. Adisesha
 
Course 102: Lecture 10: Learning About the Shell
Course 102: Lecture 10: Learning About the Shell Course 102: Lecture 10: Learning About the Shell
Course 102: Lecture 10: Learning About the Shell
Ahmed El-Arabawy
 
Chapter 2: Introduction to Bash Scripting
Chapter 2: Introduction to Bash ScriptingChapter 2: Introduction to Bash Scripting
Chapter 2: Introduction to Bash Scripting
azzamhadeel89
 
34-shell-programming.ppt
34-shell-programming.ppt34-shell-programming.ppt
34-shell-programming.ppt
KiranMantri
 
Shellscripting
ShellscriptingShellscripting
Shellscripting
Narendra Sisodiya
 
Licão 09 variables and arrays v2
Licão 09 variables and arrays v2Licão 09 variables and arrays v2
Licão 09 variables and arrays v2
Acácio Oliveira
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell Scripting
Open Gurukul
 
What is a shell script
What is a shell scriptWhat is a shell script
What is a shell script
Dr.M.Karthika parthasarathy
 

Similar to Linux System Administration (20)

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
 
Shell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdfShell Programming_Module2_Part2.pptx.pdf
Shell Programming_Module2_Part2.pptx.pdf
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
 
Case, Loop & Command line args un Unix
Case, Loop & Command line args un UnixCase, Loop & Command line args un Unix
Case, Loop & Command line args un Unix
 
Licão 05 scripts exemple
Licão 05 scripts exempleLicão 05 scripts exemple
Licão 05 scripts exemple
 
Shell programming
Shell programmingShell programming
Shell programming
 
Variables and User Input
Variables and User InputVariables and User Input
Variables and User Input
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
Unix shell scripting tutorial
Unix shell scripting tutorialUnix shell scripting tutorial
Unix shell scripting tutorial
 
Course 102: Lecture 10: Learning About the Shell
Course 102: Lecture 10: Learning About the Shell Course 102: Lecture 10: Learning About the Shell
Course 102: Lecture 10: Learning About the Shell
 
Chapter 2: Introduction to Bash Scripting
Chapter 2: Introduction to Bash ScriptingChapter 2: Introduction to Bash Scripting
Chapter 2: Introduction to Bash Scripting
 
34-shell-programming.ppt
34-shell-programming.ppt34-shell-programming.ppt
34-shell-programming.ppt
 
Shellscripting
ShellscriptingShellscripting
Shellscripting
 
Licão 09 variables and arrays v2
Licão 09 variables and arrays v2Licão 09 variables and arrays v2
Licão 09 variables and arrays v2
 
Unixscripting
UnixscriptingUnixscripting
Unixscripting
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
04 ruby syntax
04 ruby syntax04 ruby syntax
04 ruby syntax
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell Scripting
 
What is a shell script
What is a shell scriptWhat is a shell script
What is a shell script
 

More from Jayant Dalvi

Linux System Administration
Linux System AdministrationLinux System Administration
Linux System Administration
Jayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
Jayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
Jayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
Jayant Dalvi
 
Java I/O
Java I/OJava I/O
Java I/O
Jayant Dalvi
 
Information system audit 2
Information system audit 2 Information system audit 2
Information system audit 2
Jayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
Jayant Dalvi
 
java- Abstract Window toolkit
java- Abstract Window toolkitjava- Abstract Window toolkit
java- Abstract Window toolkit
Jayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
Jayant Dalvi
 
Information system audit
Information system audit Information system audit
Information system audit
Jayant Dalvi
 
Information system audit
Information system audit Information system audit
Information system audit
Jayant Dalvi
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
Jayant Dalvi
 
Information system audit
Information system audit Information system audit
Information system audit
Jayant Dalvi
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Jayant Dalvi
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 
Object Oriented Programming using C++
Object Oriented Programming using C++Object Oriented Programming using C++
Object Oriented Programming using C++
Jayant Dalvi
 

More from Jayant Dalvi (16)

Linux System Administration
Linux System AdministrationLinux System Administration
Linux System Administration
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
Java I/O
Java I/OJava I/O
Java I/O
 
Information system audit 2
Information system audit 2 Information system audit 2
Information system audit 2
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
java- Abstract Window toolkit
java- Abstract Window toolkitjava- Abstract Window toolkit
java- Abstract Window toolkit
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
Information system audit
Information system audit Information system audit
Information system audit
 
Information system audit
Information system audit Information system audit
Information system audit
 
Structured system analysis and design
Structured system analysis and design Structured system analysis and design
Structured system analysis and design
 
Information system audit
Information system audit Information system audit
Information system audit
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Object Oriented Programming using C++
Object Oriented Programming using C++Object Oriented Programming using C++
Object Oriented Programming using C++
 

Recently uploaded

Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.pptPROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
bhadouriyakaku
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
dxobcob
 
Self-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptxSelf-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptx
iemerc2024
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
AIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdfAIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdf
RicletoEspinosa1
 
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
obonagu
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 

Recently uploaded (20)

Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.pptPROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
 
Self-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptxSelf-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptx
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
AIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdfAIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdf
 
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
原版制作(unimelb毕业证书)墨尔本大学毕业证Offer一模一样
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 

Linux System Administration

  • 1. LINUX SYSTEM ADMINISTRATION UNIT 5. CHP 1. Introducing Bash Shell Scripting MR JAYANT PRADEEP DALVI
  • 2. INTRODUCTION • A shell script is a text file that contains a sequence of commands Elements of a Good Shell Script When writing a script, make sure it meets the following recommendations: • Has a unique name • Includes the shebang (#!) to tell the shell which subshell should execute the script • Includes comments—lots of comments • Uses the exit command to tell the shell executing the script that it has executed successfully • Is executable.
  • 3. Creating Your First Shell Script We can type following code, and save it with the name hello in your home directory. #!/bin/bash # this is the hello script # run it by typing ./hello in the directory where you've found it clear echo hello world //print the output exit 0
  • 4. • In the first line of the script, you can find the shebang. This scripting element tells the shell executing this script which subshell should execute this script. • The shebang always starts with #! and is followed by the name of the subshell that should execute the script. In our previous example we used /bin/bash as the subshell, but you can use any other shell you like. For instance, use #!/bin/perl if your script contains Perl code. • The second part in the script in our example consists of two lines of comments. As you can see, these comment lines explain to the user the purpose of the script and how to use it. • The command exit 0 is used as the last part of the script. It is good habit to use the exit command in all of your scripts. This command exits the script and then tells the parent shell how the script has executed.
  • 5. Executing the Script Now that you have written your first shell script, it’s time to execute it. There are three different ways of doing this. 1. Make it executable, and run it as a program. 2. Run it as an argument of the bash command. 3. Source it.
  • 6. Making the Script Executable • The most common way to run a shell script is by making it executable. To do this with the hello script from our example,we use the following command: chmod +x hello • After making the script executable, you can run it just like any other command. • If user linda created a script with the name hello in /home/linda, she has to run it using the command /home/linda/hello. Alternatively, if she is already in /home/linda, she could use ./hello to run the script. • In the latter example, the dot and slash tell the shell to run the command from the current directory.
  • 7. Running the Script as an Argument of the Bash Command • The second option for running a script is to specify its name as the argument of the bash command. For example, the script hello would run using the command bash hello. • The advantage of running the script this way is that there is no need to make it executable first. • If the script is /home/linda/hello and your current directory is /tmp, you should run it using bash /home/linda/hello.
  • 8. Working with Variables and Input • A variable is a value you get from somewhere that will be dynamic. The value of a variable normally depends on the circumstances. • For example, you can have your script get the variable itself by executing a command, making a calculation, specifying it as a command-line argument for the script, or modifying a text string. Understanding Variables • You can define a variable somewhere in a script and use it in a flexible way later. You can also define a variable in a shell. To define a variable, use varname=value to get the value of a variable. Later, you can call its value using the echo command.
  • 9. • We will see an example of how a variable is set on the command line and how its value is used in the next command. Setting and using a variable nuuk:~ # HAPPY=yes nuuk:~ # echo $HAPPY yes
  • 10. Variables, Subshells, and Sourcing • When defining variables, we have to check a variable is defined for the current shell only. This means that if you start a subshell from the current shell, the variable will not be there. • Moreover, if you define a variable in a subshell, it won’t be there anymore once you’ve quit the subshell and returned to the parent shell.
  • 11. •Variables are local to the shell where they are defined nuuk:~/bin # HAPPY=yes nuuk:~/bin # echo $HAPPY yes nuuk:~/bin # bash //subshell=bash nuuk:~/bin # echo $HAPPY nuuk:~/bin # exit exit nuuk:~/bin # echo $HAPPY yes nuuk:~/bin #
  • 12. • In above example, we have defined a variable with the name HAPPY. You can then see that its value is correctly echoed. • In the third command, a subshell is started, and as you can see, when asking for the value of the variable HAPPY in this subshell, it isn’t there because it simply doesn’t exist. • But when the subshell is closed using the exit command, you’re back in the parent shell where the variable still exists.
  • 13. • In some cases, you may want to set a variable that is present in all subshells as well. • If this is the case, you can define it using the export command. For example, the command export HAPPY=yes defines the variable HAPPY and makes sure that it is available in all subshells from the current shell forward until the computer is rebooted. • However, there is no way to define a variable and make it available in the parent shells in this manner.
  • 14. •By exporting a variable, you can also make it available in subshells nuuk:~/bin # export HAPPY=yes nuuk:~/bin # echo $HAPPY yes nuuk:~/bin # bash nuuk:~/bin # echo $HAPPY yes nuuk:~/bin # exit exit nuuk:~/bin # echo $HAPPY yes nuuk:~/bin #
  • 15. •By putting all your variables in one file, you can make them easily available HAPPY=yes ANGRY=no SUNNY=yes •The main advantage of putting all variables in one file is that you can also make them available in other shells by sourcing them.
  • 16. •Example of sourcing usage nuuk:~/bin # echo $HAPPY nuuk:~/bin # echo $ANGRY nuuk:~/bin # echo $SUNNY nuuk:~/bin # . vars nuuk:~/bin # echo $HAPPY yes nuuk:~/bin # echo $ANGRY no nuuk:~/bin # echo $SUNNY yes nuuk:~/bin #
  • 17. Working with Script Arguments • Till now we learned how to define variables and how to create a variable in a static way. Here we will learn how to provide values for your variables dynamically by specifying them as an argument for the script when running it on the command line. Using Script Arguments • When running a script, you can specify arguments to the script on the command line. • Consider the script dirscript from Example 1. You could run it with an argument on the command line like this: dirscript /blah.
  • 18. •You can refer to the first argument used in the script as $1 in the script, the second argument as $2, and so on, up to $9. You can also use $0 to refer to the name of the script itself. #!/bin/bash # # argscript # # Silly script that shows how arguments are used ARG1=$1 ARG2=$2 ARG3=$3 SCRIPTNAME=$0 echo The name of this script is $SCRIPTNAME echo The first argument used is $ARG1 echo The second argument used is $ARG2 echo The third argument used is $ARG3 exit 0
  • 19. Example 1: #!/bin/bash # # dirscript # # Silly script that creates a directory with a certain name # next sets $USER and $GROUP as the owners of the directory # and finally changes the permission mode to 770 # Provide the directory name first, followed by the username and # finally the groupname. DIRECTORY=$1 USER=$2 GROUP=$3 mkdir /$DIRECTORY chown $USER $DIRECTORY chgrp $GROUP $DIRECTORY chmod 770 $DIRECTORY exit 0
  • 20. Counting the Number of Script Arguments Occasionally, you’ll want to check the number of arguments provided with a script. This is useful if you expect a certain number of arguments and want to make sure that this number is present before running the script. To count the number of arguments provided with a script, you can use $#. Basically, $# is a counter that just shows you the exact number of arguments used when running a script. For example, you could use it to show a help message if the user hasn’t provided the correct number of arguments. In Exercise 2, the script countargs does this using $#. There is a sample running of the script directly after the code listing.
  • 21. RUN FOLLOWING SCRIPTS #!/bin/bash # # countargs # sample script that shows how many arguments were used echo the number of arguments is $# exit 0 nuuk:~/bin # ./countargs a b c d e the number of arguments is 5 nuuk:~/bin #.
  • 22. Asking for Input • Another way to get input is simply to ask for it. To do this, you can use read in the script. • When using read, the script waits for user input and puts that into a variable. In Exercise 3, you will create a simple script that first asks for input and then reflects the input provided by echoing the value of the variable.
  • 23. #!/bin/bash # # askinput # ask user to enter some text and then display it echo Enter some text read SOMETEXT echo -e "You have entered the following text:t $SOMETEXT" exit 0
  • 24. Using Command Substitution • Another way of putting a variable text in a script is by using command substitution. In command substitution, you use the result of a command in the script. This is useful if the script has something to do with the result of a command. For example, you can use this technique to tell a script that it should execute only if a certain condition is met (using a conditional loop with if to accomplish this). • To use command substitution, put the command that you want to use between backquotes (also known as back ticks). • As an alternative, you can put the command substitution between braces with a $ sign in front of the (.
  • 25. •The following sample code shows how this works: nuuk:~/bin # echo "today is $(date +%d-%m-%y)" $() today is 04-06-12 •In this example, the date command is used with some of its special formatting characters. •The command date +%d-%m-%y tells date to present its result in the day- month-year format. •However, you can also put the result of the command substitution in a variable, which makes it easier to perform a calculation on the result later in the script. The following sample code shows how to do that: nuuk:~/bin # TODAY=$(date +%d-%m-%y) nuuk:~/bin # echo today=$TODAY today is 27-01-09
  • 26. Substitution Operators • It may be important to verify that a variable indeed has a value assigned to it within a script before the script continues. To do this, bash offers substitution operators. • Substitution operators let you assign a default value if a variable doesn’t have a currently assigned value and much more.
  • 27.
  • 28. sander@linux %> echo $BLAH sander@linux %> echo ${BLAH:-variable is empty} variable is empty sander@linux %> echo $BLAH sander@linux %> echo ${BLAH=value} value sander@linux %> echo $BLAH value sander@linux %> BLAH sander@linux %> echo ${BLAH=value} sander@linux %> echo ${BLAH:=value} value sander@linux %> echo $BLAH value sander@linux %> echo ${BLAH:+sometext} sometext
  • 29. Changing Variable Content with Pattern Matching • You’ve just seen how substitution operators can be used to supply a value to a variable that does not have one. A pattern-matching operator can be used to search for a pattern in a variable and, if that pattern is found, modify the variable. This is very useful because it allows you to define a variable in exactly the way you want. • For example, think of the situation in which a user enters a complete path name of a file but only the name of the file (without the path) is needed in your script. • You can use the pattern-matching operator to change this. Pattern- matching operators allow you to remove part of a variable automatically.
  • 30. #!/bin/bash # stripit # script that extracts the file name from a filename that includes the path # usage: stripit <complete file name> filename=${1##*/} echo "The name of the file is $filename" exit 0
  • 31. Performing Calculations bash offers some options that allow you to perform calculations from scripts. For example, you can use bash calculation options to execute a command a number of times or to make sure that a counter is incremented when a command executes successfully.
  • 32. •Using a counter in a script #!/bin/bash # counter # script that counts until infinity counter=1 counter=$((counter + 1)) echo counter is set to $counter exit 0
  • 33. Using Control Structures bash offers many options to use flow control in scripts. •if: Use if to execute commands only if certain conditions are met. •To customize the working of if further, you can use else to indicate what should happen if the condition isn’t met. •case: Use case to handle options. This allows the user to specify further the working of the command as it is run. •for This construction is used to run a command for a given number of items. For example, you can use for to do something for every fi le in a specified directory. •while: Use while as long as the specified condition is met. For example, this construction can be very useful to check whether a certain host is reachable or to monitor the activity of a process. •until: This is the opposite of while. Use until to run a command until a certain condition
  • 34. test command: This command is used to perform many checks to see,
  • 35.
  • 36. Using if...then...else •The basic construction is if condition then command fi. Therefore, you’ll use it to check one specific condition, and if it is true, a command is executed #!/bin/bash # testarg # test to see if argument is present if [ -z $1 ] then echo You have to provide an argument with this command exit 1 fi echo the argument is $1 exit 0
  • 37. •Nesting if control structures #!/bin/bash # testfile if [ -f $1 ] then echo "$1 is a file" elif [ -d $1 ] then echo "$1 is a directory" else echo "I don't know what $1 is" fi exit 0
  • 38. Using case •Write a script that advises the user about the capabilities of their favorite soccer team. The script should contain the following components: 1. It should ask the user to enter the name of a country. 2. It should use case to test against different country names. 3. It should translate all input to uppercase to make evaluation of the user input easier. 4. It should tell the user what kind of input is expected
  • 39. #!/bin/bash # soccer # Your personal soccer expert # predicts world championship football cat << EOF read COUNTRY # tranlate $COUNTRY into all uppercase COUNTRY=`echo $COUNTRY | tr a-z A-Z` case $COUNTRY in NEDERLAND | HOLLAND | NETHERLANDS) echo "Yes, you are a soccer expert " ;; DEUTSCHLAND | GERMANY | MANNSCHAFT) echo "No, they are the worst team on earth" ;; ENGLAND | AUSTRALIA | FRANCE | BRAZIL) echo "hahahahahahaha, you must be joking" ;; *) echo "Huh? Do they play soccer?" ;; esac exit 0
  • 40.
  • 41. Using while •You can use while to run a command as long as a condition is met.
  • 42. Using until •Whereas while works as long as a certain condition is met, until is just the opposite; that is, it runs until the condition is met. #!/bin/bash # usermon # script that alerts when a user logs in # usage: ishere <username> until who | grep $1 >> /dev/null do echo $1 is not logged in yet sleep 5 done echo $1 has just logged in exit 0
  • 43. Using for •Sometimes it’s necessary to execute a series of commands, either for a limited number of times or for an unlimited number of times. In such cases, for loops offer an excellent solution. #!/bin/bash # counter # counter that counts from 1 to 9 for (( counter=1; counter<10; counter++ )); do echo "The counter is now set to $counter" done exit 0

Editor's Notes

  1. Note: In more complex scripts, you could even start working with different exit codes; that is, use exit 1 as a generic error message, exit 2 to specify that a specific condition was not met.
  2. name=linda
  3. scanf("%d",&a)
  4. parent- variable- op child-variable-no op
  5. employee e=new employee(1,"rajan") roll=1 name=rajan
  6. ./argscript hello 10 20 30
  7. To execute the script from this exercise, use a command such as ./dirscript /abc linda sales
  8. output- echo -command input- read - command
  9. name= o/p= name=rajan o/p=rajan name= o/p=rajan
  10. Run the script with the argument /bin/bash ./stripit /bin/bash the name of the file is bash
  11. a ! b
  12. a==b a!=b
  13. SYD:∼/bin # ./testarg ashish if(){ if } fi
  14. SYD:∼/bin # ./testfile /bin/blah
  15. switch(rank){ case 1: printf("rank1) case 2: default: