old-www/HOWTO/Bash-Prog-Intro-HOWTO-8.html

76 lines
2.4 KiB
HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<META NAME="GENERATOR" CONTENT="SGML-Tools 1.0.9">
<TITLE>BASH Programming - Introduction HOW-TO: Functions</TITLE>
<LINK HREF="Bash-Prog-Intro-HOWTO-9.html" REL=next>
<LINK HREF="Bash-Prog-Intro-HOWTO-7.html" REL=previous>
<LINK HREF="Bash-Prog-Intro-HOWTO.html#toc8" REL=contents>
</HEAD>
<BODY>
<A HREF="Bash-Prog-Intro-HOWTO-9.html">Next</A>
<A HREF="Bash-Prog-Intro-HOWTO-7.html">Previous</A>
<A HREF="Bash-Prog-Intro-HOWTO.html#toc8">Contents</A>
<HR>
<H2><A NAME="s8">8. Functions</A> </H2>
<P> As in almost any programming language, you can use functions to group
pieces of code in a more logical way or practice the divine art of recursion.
<P> Declaring a function is just a matter of writing function my_func { my_code }.
<P> Calling a function is just like calling another program, you just write its name.
<P>
<H2><A NAME="ss8.1">8.1 Functions sample</A>
</H2>
<P>
<BLOCKQUOTE><CODE>
<PRE>
#!/bin/bash
function quit {
exit
}
function hello {
echo Hello!
}
hello
quit
echo foo
</PRE>
</CODE></BLOCKQUOTE>
<P> Lines 2-4 contain the 'quit' function. Lines 5-7 contain the 'hello' function
If you are not absolutely sure about what this script does, please try it!.
<P> Notice that a functions don't need to be declared in any specific order.
<P> When running the script you'll notice that first: the function 'hello' is
called, second the 'quit' function, and the program never reaches line 10.
<H2><A NAME="ss8.2">8.2 Functions with parameters sample</A>
</H2>
<P>
<BLOCKQUOTE><CODE>
<PRE>
#!/bin/bash
function quit {
exit
}
function e {
echo $1
}
e Hello
e World
quit
echo foo
</PRE>
</CODE></BLOCKQUOTE>
<P> This script is almost identically to the previous one. The main difference is the
funcion 'e'. This function, prints the first argument it receives.
Arguments, within funtions, are treated in the same manner as arguments given to the script.
<HR>
<A HREF="Bash-Prog-Intro-HOWTO-9.html">Next</A>
<A HREF="Bash-Prog-Intro-HOWTO-7.html">Previous</A>
<A HREF="Bash-Prog-Intro-HOWTO.html#toc8">Contents</A>
</BODY>
</HTML>