SlideShare una empresa de Scribd logo
1 de 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.

Más contenido relacionado

La actualidad más candente

Perl programming language
Perl programming languagePerl programming language
Perl programming language
Elie Obeid
 
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
Utkarsh Sengar
 

La actualidad más candente (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
 

Destacado (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 a Licão 13 functions

Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
Raghu nath
 

Similar a 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
 

Más de Acácio Oliveira

Más de 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
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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.