SlideShare a Scribd company logo
1 of 24
Lesson 13
• Shell Fuctions
• Using functions
• Pass Parameters to a Function
• Returning Values from Functions
• Nested Functions
Shell functions
Functions enables to break down overall functionality of a script into smaller,
logical subsections, which can be called to perform their individual task.
• Using functions makes the scripts easier to maintain and performs repetitive tasks
is a way to create code reuse.
Shell functions are similar to subroutines, procedures, and functions in other languages.
They differ because they return a status code instead of a return value.
Without a return value, they cannot be used in expressions.
Shell functions
Creating Functions
We can create functions to perform tasks and we can also create functions that take
parameters (also called arguments)
To declare a function use syntax:
function fname()
{
statements;
}
Alternately
fname()
{
statements;
}
A function can be invoked just by using its name:
$ fname ; # executes function
Arguments can be passed to functions and can be accessed by our script:
fname arg1 arg2 ; # passing args
Using functions
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World"
}
# Invoke your function
Hello
example
$./test.sh
Hello World
$
Example result
Using functions
#!/bin/bash
hello()
{
echo “You are in function hello()”
}
echo “Calling function hello()…”
hello
echo “You are now out of function hello()”
example
We called the hello() function by name by using the line: hello.
When this line is executed, bash searches the script for the line hello(). It finds it right at
the top, and executes its contents.
Example result
Pass Parameters to a Function
Exemple in the definition of the function fname.
In fname function is included various ways of accessing the function arguments.
fname()
{
echo $1, $2; #Accessing arg1 and arg2
echo "$@"; # Printing all arguments as list at once
echo "$*"; # Similar to $@, but arguments taken as single entity
return 0; # Return value
}
Arguments passed to scripts and accessed by script:
• $0 (the name of the script):
• ‰$1 is the first argument
• ‰$2 is the second argument
• ‰$n is the nth argument
• ‰"$@“ expands as "$1" "$2" "$3" and so on
• ‰"$*" expands as "$1c$2c$3", where c is the first character of IFS
• ‰"$@" used more than "$*"since the former provides all arguments as a single string
Pass Parameters to a Function
Another function defined to accept parameters while calling that function.
Parameters represented by $1, $2, etc…
Exemple:
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World $1 $2"
}
# Invoke your function
Hello Bart Homer
Exemple result:
$./test.sh
Hello World Bart Homer
$
Variables declared inside a function exist only for duration of the function.
Called local variables. When the function completes the variables are discarded.
Variables declared inside a function
#!/bin/sh
sample_text=“global variable”
test() {
local sample_text=“local variable”
echo “Function test is executing”
echo $sample_text
}
echo “script starting”
echo $sample_text
test
echo “script ended”
echo $sample_text
exit 0
Output?
Check the scope of
the variables
define local
variable
Pass Parameters
$ vi function.sh
#!/bin/bash
function check() {
if [ -e "/home/$1" ]
then
return 0
else
return 1
fi
}
echo “Enter the name of the file: ” ; read x
if check $x
then
echo “$x exists !”
else
echo “$x does not exists !”
fi.
example
Returning Values from Functions
If you execute an exit command from inside a function, its effect is to terminate
execution of function AND also the shell program that called the function.
If its just terminate execution of function:
There is way to come out of a defined function: return any value from your
function using the return command
Syntax:
return code
code can be anything , but choose something meaningful or useful in context of the script as
a whole.
Returning Values from Functions
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World $1 $2"
return 10
}
# Invoke your function
Hello Bart Homer
# Capture value returned by last command
ret=$?
echo "Return value is $ret"
Example returns value
$./test.sh
Hello World Bart Homer
Return value is 10
$
Example result
Returning Values from Functions
$ vi my_name.sh
#!/bin/sh
yes_or_no() {
echo “Is your name $* ?”
while true
do
echo –n “Enter yes or no:”
read x
case “$x” in
y | yes ) return 0;;
n | no ) return 1;;
* ) echo “Answer yes or no”
esac
done
}
Example returns value
Losing the Function
Consider the function:
$ SayHello()
{
echo "Hello $LOGNAME, Have a nice day”
return
}
After restarting the computer you will lose SayHello() function, since its created
for current session only.
To overcome this problem add your function to /etc/bashrc file.
Go to end of file (by pressing shift+G) and type the SayHello() function
Nested Functions
Functions can call themselves and call other functions.
A function that calls itself is known as a recursive function.
#!/bin/sh
# Calling one function from another
number_one () {
echo "This is the first function speaking..."
number_two
}
number_two () {
echo "This is now the second function speaking..."
}
# Calling function one.
number_one
Example nesting
This is the first function speaking...
This is now the second function speaking...
Example result
Nested Functions
Function nesting (Chaining)
It is the process of calling a function from another function
#!/bin/bash
orange () { echo "Now in orange"
apple
}
apple () { echo "Now in apple" }
orange
Example
Exporting functions
A function can be exported—like environment variables— using export
scope of the function can be extended to subprocesses
export -f fname
Exporting functions
A function can be unset —like environment variables— using unset
unset function_name
Unset functions
Option:
Function to prepend to environment variables
Environment variables are often used to store a list of paths of where to search for
executables, libraries, and so on.
Examples are
$PATH, $LD_LIBRARY_PATH, which will typically look like this:
PATH=/usr/bin;/bin
LD_LIBRARY_PATH=/usr/lib;/lib
This means that whenever shell has to execute binaries, will look in /usr/bin followed by /bin.
A very common task that one has to do when building a program from source and installing to
a custom path is to add its bin directory to the PATH environment variable.
Let's say we install myapp to /opt/myapp, which has binaries in a directory called
bin and libraries in lib.
A way to do this is to say it as follows:
export PATH=/opt/myapp/bin:$PATH
export LD_LIBRARY_PATH=/opt/myapp/lib;$LD_LIBRARY_PATH
PATH and LD_LIBRARY_PATH should now look something like this:
PATH=/opt/myapp/bin:/usr/bin:/bin
LD_LIBRARY_PATH=/opt/myapp/lib:/usr/lib;/lib
However, we can make this easier by adding this function in .bashrc-:
prepend() { [ -d "$2" ] && eval $1="$2':'$$1" && export $1; }
This can be used in the following way:
prepend PATH /opt/myapp/bin
prepend LD_LIBRARY_PATH /opt/myapp/lib
We define a function called prepend(), which first checks if the directory specified by the second
parameter to the function exists.
If it does, the eval expression sets the variable with the name in the first parameter equal to the second
parameter string followed by : (the path separator) and then the original value for the variable.
Option:
Function to prepend to environment variables
However, there is one problem.
if variable is empty when we try to prepend there will be a trailing : at end.
To fix this, we can modify the function to look like this:
prepend() { [ -d "$2" ] && eval $1="$2${$1:+':'$$1}" && export
$1 ;
}
In this form of the function, we introduce a shell parameter expansion of the form:
${parameter:+expression}
This expands to expression if parameter is set and is not null.
With this change, we take care to try to append : and the old value if, and only if, the old
value existed when trying to prepend.
Option:
Function to prepend to environment variables
Functions in Bash with support recursion (the function that can call itself).
Example:
F()
{ echo $1; F hello; sleep 1; }
………………………………………………………..
:(){ :|: & };: http://en.wikipedia.org/wiki/Fork_bomb
Replace the the function identifier and re-indenting, the code
reads:
bomb() {
bomb | bomb &
};
bomb
Option:
Recursive function - fork exemple
Function exemple
Running a command until it succeeds
When using your shell for everyday tasks, there will be cases where a command
might succeed only after some conditions are met, or the operation depends on an
external event (a file being available to download).
In such cases, one might want to run a command repeatedly until it succeeds.
Define a function in the following way:
repeat()
{
while true
do
$@ && return
done
}
Or add this to your shell's rc file for ease of use:
repeat() { while true; do $@ && return; done }
We create a function called repeat that has an infinite while loop, which attempts to run the
command passed as a parameter (accessed by $@) to the function. It then returns if the
command was successful, thereby exiting the loop.
Function exemple
Running a command until it succeeds faster
On most systems, true is implemented as a binary in /bin.
This means that each time the while loop runs, the shell has to spawn a process.
To avoid this, we can use the : shell built-in, which always returns an exit code 0:
repeat() { while :; do $@ && return; done }
not as readable, but faster than the first approach.
Functions vs Aliases
An alias is an abbreviation or an alternative name, usually mnemonic, for a command.
Aliases are defined using the alias command:
Syntax: alias name="cmd"
Ex: alias lsl="ls –l"
Unalias
Once an alias has been defined, it can be unset using unalias command:
Syntax: unalias name
Here, name is the name of the alias to be unset.
Ex: unalias lsl
Aliases are similar to functions in that they associate a command with a name.
Two key differences:
1. In alias cmd cannot be a compound command or a list.
2. In alias there is no way to manipulate the argument list ($@).
Due to their limited capabilities, aliases are not commonly used in shell programs.

More Related Content

What's hot

Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perlsana mateen
 
Perl programming language
Perl programming languagePerl programming language
Perl programming languageElie Obeid
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record.toster
 
Programming in perl style
Programming in perl styleProgramming in perl style
Programming in perl styleBo Hua Yang
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl ProgrammingUtkarsh Sengar
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftMichele Titolo
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageGiuseppe Arici
 
Unit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structuresUnit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structuressana mateen
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
python Function
python Function python Function
python Function Ronak Rathi
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlsana mateen
 

What's hot (19)

Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perl
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
Intro to Perl and Bioperl
Intro to Perl and BioperlIntro to Perl and Bioperl
Intro to Perl and Bioperl
 
PHP function
PHP functionPHP function
PHP function
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
Programming in perl style
Programming in perl styleProgramming in perl style
Programming in perl style
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl Programming
 
Perl_Part5
Perl_Part5Perl_Part5
Perl_Part5
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Intro to Perl
Intro to PerlIntro to Perl
Intro to Perl
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Unit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structuresUnit 1-scalar expressions and control structures
Unit 1-scalar expressions and control structures
 
newperl5
newperl5newperl5
newperl5
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Unix ppt
Unix pptUnix ppt
Unix ppt
 
python Function
python Function python Function
python Function
 
Strings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perlStrings,patterns and regular expressions in perl
Strings,patterns and regular expressions in perl
 

Viewers also liked

Open lpi 101 preparation guide v3
 Open lpi 101 preparation guide v3 Open lpi 101 preparation guide v3
Open lpi 101 preparation guide v3Acácio Oliveira
 
Licão 12 decision loops - statement iteration
Licão 12 decision loops - statement iterationLicão 12 decision loops - statement iteration
Licão 12 decision loops - statement iterationAcácio Oliveira
 
Licão 02 shell basics bash intro
Licão 02 shell basics bash introLicão 02 shell basics bash intro
Licão 02 shell basics bash introAcácio Oliveira
 
Append 03 bash beginners guide
Append 03 bash beginners guideAppend 03 bash beginners guide
Append 03 bash beginners guideAcácio Oliveira
 
Append 00 advanced bash scripting gnu guide
Append 00 advanced bash scripting gnu guideAppend 00 advanced bash scripting gnu guide
Append 00 advanced bash scripting gnu guideAcácio Oliveira
 

Viewers also liked (9)

Open lpi 101 preparation guide v3
 Open lpi 101 preparation guide v3 Open lpi 101 preparation guide v3
Open lpi 101 preparation guide v3
 
Licão 12 decision loops - statement iteration
Licão 12 decision loops - statement iterationLicão 12 decision loops - statement iteration
Licão 12 decision loops - statement iteration
 
Como predicar de la biblia
Como predicar de la biblia  Como predicar de la biblia
Como predicar de la biblia
 
Licão 03 vi editor
Licão 03 vi editorLicão 03 vi editor
Licão 03 vi editor
 
Licão 01 introduction
Licão 01 introductionLicão 01 introduction
Licão 01 introduction
 
Licão 02 shell basics bash intro
Licão 02 shell basics bash introLicão 02 shell basics bash intro
Licão 02 shell basics bash intro
 
Licão 14 debug script
Licão 14 debug scriptLicão 14 debug script
Licão 14 debug script
 
Append 03 bash beginners guide
Append 03 bash beginners guideAppend 03 bash beginners guide
Append 03 bash beginners guide
 
Append 00 advanced bash scripting gnu guide
Append 00 advanced bash scripting gnu guideAppend 00 advanced bash scripting gnu guide
Append 00 advanced bash scripting gnu guide
 

Similar to Licão 13 functions

Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP FunctionsAhmed Swilam
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closuresmelechi
 
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 v2Acácio Oliveira
 
php user defined functions
php user defined functionsphp user defined functions
php user defined functionsvishnupriyapm4
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Functions in PHP.pptx
Functions in PHP.pptxFunctions in PHP.pptx
Functions in PHP.pptxJapneet9
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.pptJamers2
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Allan Marques Baptista
 
OpenWRT Makefile reference
OpenWRT Makefile referenceOpenWRT Makefile reference
OpenWRT Makefile reference家榮 吳
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboardsDenis Ristic
 
PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxShaliniPrabakaran
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.pptmugeshmsd5
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell ScriptingRaghu nath
 

Similar to Licão 13 functions (20)

Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Shell programming
Shell programmingShell programming
Shell programming
 
PHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & ClosuresPHP 5.3 Part 2 - Lambda Functions & Closures
PHP 5.3 Part 2 - Lambda Functions & Closures
 
Functions in Shell Script.pptx
Functions in Shell Script.pptxFunctions in Shell Script.pptx
Functions in Shell Script.pptx
 
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
 
php user defined functions
php user defined functionsphp user defined functions
php user defined functions
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Functions in PHP.pptx
Functions in PHP.pptxFunctions in PHP.pptx
Functions in PHP.pptx
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
 
PHP-03-Functions.ppt
PHP-03-Functions.pptPHP-03-Functions.ppt
PHP-03-Functions.ppt
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)Introduction to Functional Programming (w/ JS)
Introduction to Functional Programming (w/ JS)
 
OpenWRT Makefile reference
OpenWRT Makefile referenceOpenWRT Makefile reference
OpenWRT Makefile reference
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
 
PHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptxPHP FUNCTIONS AND ARRAY.pptx
PHP FUNCTIONS AND ARRAY.pptx
 
390aLecture05_12sp.ppt
390aLecture05_12sp.ppt390aLecture05_12sp.ppt
390aLecture05_12sp.ppt
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 

More from Acácio Oliveira

Security+ Lesson 01 Topic 24 - Vulnerability Scanning vs Pen Testing.pptx
Security+ Lesson 01 Topic 24 - Vulnerability Scanning vs Pen Testing.pptxSecurity+ Lesson 01 Topic 24 - Vulnerability Scanning vs Pen Testing.pptx
Security+ Lesson 01 Topic 24 - Vulnerability Scanning vs Pen Testing.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 25 - Application Security Controls and Techniques.pptx
Security+ Lesson 01 Topic 25 - Application Security Controls and Techniques.pptxSecurity+ Lesson 01 Topic 25 - Application Security Controls and Techniques.pptx
Security+ Lesson 01 Topic 25 - Application Security Controls and Techniques.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 21 - Types of Application Attacks.pptx
Security+ Lesson 01 Topic 21 - Types of Application Attacks.pptxSecurity+ Lesson 01 Topic 21 - Types of Application Attacks.pptx
Security+ Lesson 01 Topic 21 - Types of Application Attacks.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 19 - Summary of Social Engineering Attacks.pptx
Security+ Lesson 01 Topic 19 - Summary of Social Engineering Attacks.pptxSecurity+ Lesson 01 Topic 19 - Summary of Social Engineering Attacks.pptx
Security+ Lesson 01 Topic 19 - Summary of Social Engineering Attacks.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 23 - Overview of Security Assessment Tools.pptx
Security+ Lesson 01 Topic 23 - Overview of Security Assessment Tools.pptxSecurity+ Lesson 01 Topic 23 - Overview of Security Assessment Tools.pptx
Security+ Lesson 01 Topic 23 - Overview of Security Assessment Tools.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 20 - Summary of Wireless Attacks.pptx
Security+ Lesson 01 Topic 20 - Summary of Wireless Attacks.pptxSecurity+ Lesson 01 Topic 20 - Summary of Wireless Attacks.pptx
Security+ Lesson 01 Topic 20 - Summary of Wireless Attacks.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 22 - Security Enhancement Techniques.pptx
Security+ Lesson 01 Topic 22 - Security Enhancement Techniques.pptxSecurity+ Lesson 01 Topic 22 - Security Enhancement Techniques.pptx
Security+ Lesson 01 Topic 22 - Security Enhancement Techniques.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 15 - Risk Management Best Practices.pptx
Security+ Lesson 01 Topic 15 - Risk Management Best Practices.pptxSecurity+ Lesson 01 Topic 15 - Risk Management Best Practices.pptx
Security+ Lesson 01 Topic 15 - Risk Management Best Practices.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 13 - Physical Security and Environmental Controls.pptx
Security+ Lesson 01 Topic 13 - Physical Security and Environmental Controls.pptxSecurity+ Lesson 01 Topic 13 - Physical Security and Environmental Controls.pptx
Security+ Lesson 01 Topic 13 - Physical Security and Environmental Controls.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 14 - Disaster Recovery Concepts.pptx
Security+ Lesson 01 Topic 14 - Disaster Recovery Concepts.pptxSecurity+ Lesson 01 Topic 14 - Disaster Recovery Concepts.pptx
Security+ Lesson 01 Topic 14 - Disaster Recovery Concepts.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 06 - Wireless Security Considerations.pptx
Security+ Lesson 01 Topic 06 - Wireless Security Considerations.pptxSecurity+ Lesson 01 Topic 06 - Wireless Security Considerations.pptx
Security+ Lesson 01 Topic 06 - Wireless Security Considerations.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 04 - Secure Network Design Elements and Components....
Security+ Lesson 01 Topic 04 - Secure Network Design Elements and Components....Security+ Lesson 01 Topic 04 - Secure Network Design Elements and Components....
Security+ Lesson 01 Topic 04 - Secure Network Design Elements and Components....Acácio Oliveira
 
Security+ Lesson 01 Topic 02 - Secure Network Administration Concepts.pptx
Security+ Lesson 01 Topic 02 - Secure Network Administration Concepts.pptxSecurity+ Lesson 01 Topic 02 - Secure Network Administration Concepts.pptx
Security+ Lesson 01 Topic 02 - Secure Network Administration Concepts.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 01 - Intro to Network Devices.pptx
Security+ Lesson 01 Topic 01 - Intro to Network Devices.pptxSecurity+ Lesson 01 Topic 01 - Intro to Network Devices.pptx
Security+ Lesson 01 Topic 01 - Intro to Network Devices.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 08 - Integrating Data and Systems with Third Partie...
Security+ Lesson 01 Topic 08 - Integrating Data and Systems with Third Partie...Security+ Lesson 01 Topic 08 - Integrating Data and Systems with Third Partie...
Security+ Lesson 01 Topic 08 - Integrating Data and Systems with Third Partie...Acácio Oliveira
 
Security+ Lesson 01 Topic 07 - Risk Related Concepts.pptx
Security+ Lesson 01 Topic 07 - Risk Related Concepts.pptxSecurity+ Lesson 01 Topic 07 - Risk Related Concepts.pptx
Security+ Lesson 01 Topic 07 - Risk Related Concepts.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 05 - Common Network Protocols.pptx
Security+ Lesson 01 Topic 05 - Common Network Protocols.pptxSecurity+ Lesson 01 Topic 05 - Common Network Protocols.pptx
Security+ Lesson 01 Topic 05 - Common Network Protocols.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 11 - Incident Response Concepts.pptx
Security+ Lesson 01 Topic 11 - Incident Response Concepts.pptxSecurity+ Lesson 01 Topic 11 - Incident Response Concepts.pptx
Security+ Lesson 01 Topic 11 - Incident Response Concepts.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 12 - Security Related Awareness and Training.pptx
Security+ Lesson 01 Topic 12 - Security Related Awareness and Training.pptxSecurity+ Lesson 01 Topic 12 - Security Related Awareness and Training.pptx
Security+ Lesson 01 Topic 12 - Security Related Awareness and Training.pptxAcácio Oliveira
 
Security+ Lesson 01 Topic 17 - Types of Malware.pptx
Security+ Lesson 01 Topic 17 - Types of Malware.pptxSecurity+ Lesson 01 Topic 17 - Types of Malware.pptx
Security+ Lesson 01 Topic 17 - Types of Malware.pptxAcácio Oliveira
 

More from Acácio Oliveira (20)

Security+ Lesson 01 Topic 24 - Vulnerability Scanning vs Pen Testing.pptx
Security+ Lesson 01 Topic 24 - Vulnerability Scanning vs Pen Testing.pptxSecurity+ Lesson 01 Topic 24 - Vulnerability Scanning vs Pen Testing.pptx
Security+ Lesson 01 Topic 24 - Vulnerability Scanning vs Pen Testing.pptx
 
Security+ Lesson 01 Topic 25 - Application Security Controls and Techniques.pptx
Security+ Lesson 01 Topic 25 - Application Security Controls and Techniques.pptxSecurity+ Lesson 01 Topic 25 - Application Security Controls and Techniques.pptx
Security+ Lesson 01 Topic 25 - Application Security Controls and Techniques.pptx
 
Security+ Lesson 01 Topic 21 - Types of Application Attacks.pptx
Security+ Lesson 01 Topic 21 - Types of Application Attacks.pptxSecurity+ Lesson 01 Topic 21 - Types of Application Attacks.pptx
Security+ Lesson 01 Topic 21 - Types of Application Attacks.pptx
 
Security+ Lesson 01 Topic 19 - Summary of Social Engineering Attacks.pptx
Security+ Lesson 01 Topic 19 - Summary of Social Engineering Attacks.pptxSecurity+ Lesson 01 Topic 19 - Summary of Social Engineering Attacks.pptx
Security+ Lesson 01 Topic 19 - Summary of Social Engineering Attacks.pptx
 
Security+ Lesson 01 Topic 23 - Overview of Security Assessment Tools.pptx
Security+ Lesson 01 Topic 23 - Overview of Security Assessment Tools.pptxSecurity+ Lesson 01 Topic 23 - Overview of Security Assessment Tools.pptx
Security+ Lesson 01 Topic 23 - Overview of Security Assessment Tools.pptx
 
Security+ Lesson 01 Topic 20 - Summary of Wireless Attacks.pptx
Security+ Lesson 01 Topic 20 - Summary of Wireless Attacks.pptxSecurity+ Lesson 01 Topic 20 - Summary of Wireless Attacks.pptx
Security+ Lesson 01 Topic 20 - Summary of Wireless Attacks.pptx
 
Security+ Lesson 01 Topic 22 - Security Enhancement Techniques.pptx
Security+ Lesson 01 Topic 22 - Security Enhancement Techniques.pptxSecurity+ Lesson 01 Topic 22 - Security Enhancement Techniques.pptx
Security+ Lesson 01 Topic 22 - Security Enhancement Techniques.pptx
 
Security+ Lesson 01 Topic 15 - Risk Management Best Practices.pptx
Security+ Lesson 01 Topic 15 - Risk Management Best Practices.pptxSecurity+ Lesson 01 Topic 15 - Risk Management Best Practices.pptx
Security+ Lesson 01 Topic 15 - Risk Management Best Practices.pptx
 
Security+ Lesson 01 Topic 13 - Physical Security and Environmental Controls.pptx
Security+ Lesson 01 Topic 13 - Physical Security and Environmental Controls.pptxSecurity+ Lesson 01 Topic 13 - Physical Security and Environmental Controls.pptx
Security+ Lesson 01 Topic 13 - Physical Security and Environmental Controls.pptx
 
Security+ Lesson 01 Topic 14 - Disaster Recovery Concepts.pptx
Security+ Lesson 01 Topic 14 - Disaster Recovery Concepts.pptxSecurity+ Lesson 01 Topic 14 - Disaster Recovery Concepts.pptx
Security+ Lesson 01 Topic 14 - Disaster Recovery Concepts.pptx
 
Security+ Lesson 01 Topic 06 - Wireless Security Considerations.pptx
Security+ Lesson 01 Topic 06 - Wireless Security Considerations.pptxSecurity+ Lesson 01 Topic 06 - Wireless Security Considerations.pptx
Security+ Lesson 01 Topic 06 - Wireless Security Considerations.pptx
 
Security+ Lesson 01 Topic 04 - Secure Network Design Elements and Components....
Security+ Lesson 01 Topic 04 - Secure Network Design Elements and Components....Security+ Lesson 01 Topic 04 - Secure Network Design Elements and Components....
Security+ Lesson 01 Topic 04 - Secure Network Design Elements and Components....
 
Security+ Lesson 01 Topic 02 - Secure Network Administration Concepts.pptx
Security+ Lesson 01 Topic 02 - Secure Network Administration Concepts.pptxSecurity+ Lesson 01 Topic 02 - Secure Network Administration Concepts.pptx
Security+ Lesson 01 Topic 02 - Secure Network Administration Concepts.pptx
 
Security+ Lesson 01 Topic 01 - Intro to Network Devices.pptx
Security+ Lesson 01 Topic 01 - Intro to Network Devices.pptxSecurity+ Lesson 01 Topic 01 - Intro to Network Devices.pptx
Security+ Lesson 01 Topic 01 - Intro to Network Devices.pptx
 
Security+ Lesson 01 Topic 08 - Integrating Data and Systems with Third Partie...
Security+ Lesson 01 Topic 08 - Integrating Data and Systems with Third Partie...Security+ Lesson 01 Topic 08 - Integrating Data and Systems with Third Partie...
Security+ Lesson 01 Topic 08 - Integrating Data and Systems with Third Partie...
 
Security+ Lesson 01 Topic 07 - Risk Related Concepts.pptx
Security+ Lesson 01 Topic 07 - Risk Related Concepts.pptxSecurity+ Lesson 01 Topic 07 - Risk Related Concepts.pptx
Security+ Lesson 01 Topic 07 - Risk Related Concepts.pptx
 
Security+ Lesson 01 Topic 05 - Common Network Protocols.pptx
Security+ Lesson 01 Topic 05 - Common Network Protocols.pptxSecurity+ Lesson 01 Topic 05 - Common Network Protocols.pptx
Security+ Lesson 01 Topic 05 - Common Network Protocols.pptx
 
Security+ Lesson 01 Topic 11 - Incident Response Concepts.pptx
Security+ Lesson 01 Topic 11 - Incident Response Concepts.pptxSecurity+ Lesson 01 Topic 11 - Incident Response Concepts.pptx
Security+ Lesson 01 Topic 11 - Incident Response Concepts.pptx
 
Security+ Lesson 01 Topic 12 - Security Related Awareness and Training.pptx
Security+ Lesson 01 Topic 12 - Security Related Awareness and Training.pptxSecurity+ Lesson 01 Topic 12 - Security Related Awareness and Training.pptx
Security+ Lesson 01 Topic 12 - Security Related Awareness and Training.pptx
 
Security+ Lesson 01 Topic 17 - Types of Malware.pptx
Security+ Lesson 01 Topic 17 - Types of Malware.pptxSecurity+ Lesson 01 Topic 17 - Types of Malware.pptx
Security+ Lesson 01 Topic 17 - Types of Malware.pptx
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

Licão 13 functions

  • 1. Lesson 13 • Shell Fuctions • Using functions • Pass Parameters to a Function • Returning Values from Functions • Nested Functions
  • 2. Shell functions Functions enables to break down overall functionality of a script into smaller, logical subsections, which can be called to perform their individual task. • Using functions makes the scripts easier to maintain and performs repetitive tasks is a way to create code reuse. Shell functions are similar to subroutines, procedures, and functions in other languages. They differ because they return a status code instead of a return value. Without a return value, they cannot be used in expressions.
  • 3. Shell functions Creating Functions We can create functions to perform tasks and we can also create functions that take parameters (also called arguments) To declare a function use syntax: function fname() { statements; } Alternately fname() { statements; } A function can be invoked just by using its name: $ fname ; # executes function Arguments can be passed to functions and can be accessed by our script: fname arg1 arg2 ; # passing args
  • 4. Using functions #!/bin/sh # Define your function here Hello () { echo "Hello World" } # Invoke your function Hello example $./test.sh Hello World $ Example result
  • 5. Using functions #!/bin/bash hello() { echo “You are in function hello()” } echo “Calling function hello()…” hello echo “You are now out of function hello()” example We called the hello() function by name by using the line: hello. When this line is executed, bash searches the script for the line hello(). It finds it right at the top, and executes its contents. Example result
  • 6. Pass Parameters to a Function Exemple in the definition of the function fname. In fname function is included various ways of accessing the function arguments. fname() { echo $1, $2; #Accessing arg1 and arg2 echo "$@"; # Printing all arguments as list at once echo "$*"; # Similar to $@, but arguments taken as single entity return 0; # Return value } Arguments passed to scripts and accessed by script: • $0 (the name of the script): • ‰$1 is the first argument • ‰$2 is the second argument • ‰$n is the nth argument • ‰"$@“ expands as "$1" "$2" "$3" and so on • ‰"$*" expands as "$1c$2c$3", where c is the first character of IFS • ‰"$@" used more than "$*"since the former provides all arguments as a single string
  • 7. Pass Parameters to a Function Another function defined to accept parameters while calling that function. Parameters represented by $1, $2, etc… Exemple: #!/bin/sh # Define your function here Hello () { echo "Hello World $1 $2" } # Invoke your function Hello Bart Homer Exemple result: $./test.sh Hello World Bart Homer $ Variables declared inside a function exist only for duration of the function. Called local variables. When the function completes the variables are discarded.
  • 8. Variables declared inside a function #!/bin/sh sample_text=“global variable” test() { local sample_text=“local variable” echo “Function test is executing” echo $sample_text } echo “script starting” echo $sample_text test echo “script ended” echo $sample_text exit 0 Output? Check the scope of the variables define local variable
  • 9. Pass Parameters $ vi function.sh #!/bin/bash function check() { if [ -e "/home/$1" ] then return 0 else return 1 fi } echo “Enter the name of the file: ” ; read x if check $x then echo “$x exists !” else echo “$x does not exists !” fi. example
  • 10. Returning Values from Functions If you execute an exit command from inside a function, its effect is to terminate execution of function AND also the shell program that called the function. If its just terminate execution of function: There is way to come out of a defined function: return any value from your function using the return command Syntax: return code code can be anything , but choose something meaningful or useful in context of the script as a whole.
  • 11. Returning Values from Functions #!/bin/sh # Define your function here Hello () { echo "Hello World $1 $2" return 10 } # Invoke your function Hello Bart Homer # Capture value returned by last command ret=$? echo "Return value is $ret" Example returns value $./test.sh Hello World Bart Homer Return value is 10 $ Example result
  • 12. Returning Values from Functions $ vi my_name.sh #!/bin/sh yes_or_no() { echo “Is your name $* ?” while true do echo –n “Enter yes or no:” read x case “$x” in y | yes ) return 0;; n | no ) return 1;; * ) echo “Answer yes or no” esac done } Example returns value
  • 13. Losing the Function Consider the function: $ SayHello() { echo "Hello $LOGNAME, Have a nice day” return } After restarting the computer you will lose SayHello() function, since its created for current session only. To overcome this problem add your function to /etc/bashrc file. Go to end of file (by pressing shift+G) and type the SayHello() function
  • 14. Nested Functions Functions can call themselves and call other functions. A function that calls itself is known as a recursive function. #!/bin/sh # Calling one function from another number_one () { echo "This is the first function speaking..." number_two } number_two () { echo "This is now the second function speaking..." } # Calling function one. number_one Example nesting This is the first function speaking... This is now the second function speaking... Example result
  • 15. Nested Functions Function nesting (Chaining) It is the process of calling a function from another function #!/bin/bash orange () { echo "Now in orange" apple } apple () { echo "Now in apple" } orange Example
  • 16. Exporting functions A function can be exported—like environment variables— using export scope of the function can be extended to subprocesses export -f fname Exporting functions
  • 17. A function can be unset —like environment variables— using unset unset function_name Unset functions
  • 18. Option: Function to prepend to environment variables Environment variables are often used to store a list of paths of where to search for executables, libraries, and so on. Examples are $PATH, $LD_LIBRARY_PATH, which will typically look like this: PATH=/usr/bin;/bin LD_LIBRARY_PATH=/usr/lib;/lib This means that whenever shell has to execute binaries, will look in /usr/bin followed by /bin. A very common task that one has to do when building a program from source and installing to a custom path is to add its bin directory to the PATH environment variable. Let's say we install myapp to /opt/myapp, which has binaries in a directory called bin and libraries in lib. A way to do this is to say it as follows:
  • 19. export PATH=/opt/myapp/bin:$PATH export LD_LIBRARY_PATH=/opt/myapp/lib;$LD_LIBRARY_PATH PATH and LD_LIBRARY_PATH should now look something like this: PATH=/opt/myapp/bin:/usr/bin:/bin LD_LIBRARY_PATH=/opt/myapp/lib:/usr/lib;/lib However, we can make this easier by adding this function in .bashrc-: prepend() { [ -d "$2" ] && eval $1="$2':'$$1" && export $1; } This can be used in the following way: prepend PATH /opt/myapp/bin prepend LD_LIBRARY_PATH /opt/myapp/lib We define a function called prepend(), which first checks if the directory specified by the second parameter to the function exists. If it does, the eval expression sets the variable with the name in the first parameter equal to the second parameter string followed by : (the path separator) and then the original value for the variable. Option: Function to prepend to environment variables
  • 20. However, there is one problem. if variable is empty when we try to prepend there will be a trailing : at end. To fix this, we can modify the function to look like this: prepend() { [ -d "$2" ] && eval $1="$2${$1:+':'$$1}" && export $1 ; } In this form of the function, we introduce a shell parameter expansion of the form: ${parameter:+expression} This expands to expression if parameter is set and is not null. With this change, we take care to try to append : and the old value if, and only if, the old value existed when trying to prepend. Option: Function to prepend to environment variables
  • 21. Functions in Bash with support recursion (the function that can call itself). Example: F() { echo $1; F hello; sleep 1; } ……………………………………………………….. :(){ :|: & };: http://en.wikipedia.org/wiki/Fork_bomb Replace the the function identifier and re-indenting, the code reads: bomb() { bomb | bomb & }; bomb Option: Recursive function - fork exemple
  • 22. Function exemple Running a command until it succeeds When using your shell for everyday tasks, there will be cases where a command might succeed only after some conditions are met, or the operation depends on an external event (a file being available to download). In such cases, one might want to run a command repeatedly until it succeeds. Define a function in the following way: repeat() { while true do $@ && return done } Or add this to your shell's rc file for ease of use: repeat() { while true; do $@ && return; done } We create a function called repeat that has an infinite while loop, which attempts to run the command passed as a parameter (accessed by $@) to the function. It then returns if the command was successful, thereby exiting the loop.
  • 23. Function exemple Running a command until it succeeds faster On most systems, true is implemented as a binary in /bin. This means that each time the while loop runs, the shell has to spawn a process. To avoid this, we can use the : shell built-in, which always returns an exit code 0: repeat() { while :; do $@ && return; done } not as readable, but faster than the first approach.
  • 24. Functions vs Aliases An alias is an abbreviation or an alternative name, usually mnemonic, for a command. Aliases are defined using the alias command: Syntax: alias name="cmd" Ex: alias lsl="ls –l" Unalias Once an alias has been defined, it can be unset using unalias command: Syntax: unalias name Here, name is the name of the alias to be unset. Ex: unalias lsl Aliases are similar to functions in that they associate a command with a name. Two key differences: 1. In alias cmd cannot be a compound command or a list. 2. In alias there is no way to manipulate the argument list ($@). Due to their limited capabilities, aliases are not commonly used in shell programs.