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

104 lines
3.2 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: Conditionals</TITLE>
<LINK HREF="Bash-Prog-Intro-HOWTO-7.html" REL=next>
<LINK HREF="Bash-Prog-Intro-HOWTO-5.html" REL=previous>
<LINK HREF="Bash-Prog-Intro-HOWTO.html#toc6" REL=contents>
</HEAD>
<BODY>
<A HREF="Bash-Prog-Intro-HOWTO-7.html">Next</A>
<A HREF="Bash-Prog-Intro-HOWTO-5.html">Previous</A>
<A HREF="Bash-Prog-Intro-HOWTO.html#toc6">Contents</A>
<HR>
<H2><A NAME="s6">6. Conditionals</A> </H2>
<P> Conditionals let you decide whether to perform an action
or not, this decision is taken by evaluating an expression.
<P>
<H2><A NAME="ss6.1">6.1 Dry Theory</A>
</H2>
<P> Conditionals have many forms. The most basic form is:
<B>if</B> <I>expression</I> <B>then</B> <I>statement</I>
where 'statement' is only executed if 'expression'
evaluates to true.
'2&lt;1' is an expresion that evaluates to false, while '2>1'
evaluates to true.xs
<P> Conditionals have other forms such as:
<B>if</B> <I>expression</I>
<B>then</B> <I>statement1</I> <B>else</B> <I>statement2</I>.
Here 'statement1' is executed if 'expression' is true,otherwise
'statement2' is executed.
<P> Yet another form of conditionals is:
<B>if</B> <I>expression1</I>
<B>then</B> <I>statement1</I>
<B>else if</B> <I>expression2</I> <B>then</B> <I>statement2</I>
<B>else</B> <I>statement3</I>.
In this form there's added only the
"ELSE IF 'expression2' THEN 'statement2'" which makes statement2 being
executed if expression2 evaluates to true. The rest is as you may
imagine (see previous forms).
<P> A word about syntax:
<P> The base for the 'if' constructions in bash is this:
<P> if [expression];
<P> then
<P> code if 'expression' is true.
<P> fi
<H2><A NAME="ss6.2">6.2 Sample: Basic conditional example if .. then</A>
</H2>
<P>
<BLOCKQUOTE><CODE>
<PRE>
#!/bin/bash
if [ "foo" = "foo" ]; then
echo expression evaluated as true
fi
</PRE>
</CODE></BLOCKQUOTE>
<P> The code to be executed if the expression within braces
is true can
be found after the 'then' word and before 'fi' which indicates the end
of the conditionally executed code.
<H2><A NAME="ss6.3">6.3 Sample: Basic conditional example if .. then ... else</A>
</H2>
<P>
<BLOCKQUOTE><CODE>
<PRE>
#!/bin/bash
if [ "foo" = "foo" ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi
</PRE>
</CODE></BLOCKQUOTE>
<H2><A NAME="ss6.4">6.4 Sample: Conditionals with variables</A>
</H2>
<P>
<BLOCKQUOTE><CODE>
<PRE>
#!/bin/bash
T1="foo"
T2="bar"
if [ "$T1" = "$T2" ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi
</PRE>
</CODE></BLOCKQUOTE>
<HR>
<A HREF="Bash-Prog-Intro-HOWTO-7.html">Next</A>
<A HREF="Bash-Prog-Intro-HOWTO-5.html">Previous</A>
<A HREF="Bash-Prog-Intro-HOWTO.html#toc6">Contents</A>
</BODY>
</HTML>