Changes

Jump to navigation Jump to search
1,222 bytes added ,  11:48, 1 October 2014
adds 'if' examples
<source lang="bash">
for i in `seq 1 10`; do echo "$i, "; done
</source>
 
== If construct ==
The <code>then</code> can go on the same line as the <code>if</code> as long as you use a semi-colon to terminate the if clause. Alternately, you can put the <code>then</code> on it's own line
<source lang="bash">
if EXPR; then
# do stuff
fi
</source>
is equivalent to
<source lang="bash">
if EXPR
then
# do stuff
fi
</source>
 
Adding an <code>else</code> clause
<source lang="bash">
if EXPR; then
# do stuff
else
# do other stuff
fi
</source>
 
Adding multiple <code>else</code> clauses with <code>elif; then</code>
<source lang="bash">
if EXPR; then
# do stuff
elif EXPR; then
# do other stuff
else
# final else
fi
</source>
 
Note: sometimes you want to comment out a section of an if/else block, or maybe it does nothing at all. In this case, you'll get an error. To avoid the error, you can use the bash built-in <code>:</code> (colon command)
 
<pre>
: [arguments]
</pre>
Do nothing beyond expanding arguments and performing redirections. The return status is zero.
 
<source lang="bash">
if [ -f "/tmp/Non-existing-file.txt" ] ; then
echo "I found the non-existing file"
else
: # the colon command prevents an error if there are no other statements in this block
fi
</source>
4,558

edits

Navigation menu