27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

if [ condition−true ]<br />

then<br />

command 1<br />

command 2<br />

...<br />

else<br />

# Optional (may be left out if not needed).<br />

# Adds default code block executing if original condition tests false.<br />

command 3<br />

command 4<br />

...<br />

fi<br />

When if and then are on same line in a condition test, a semicolon must terminate the if statement. Both<br />

if and then are keywords. Keywords (or commands) begin statements, and before a new statement on the<br />

same line begins, the old one must terminate.<br />

if [ −x "$filename" ]; then<br />

Else if and elif<br />

elif<br />

elif is a contraction for else if. The effect is to nest an inner if/then construct within an outer one.<br />

if [ condition1 ]<br />

then<br />

command1<br />

command2<br />

command3<br />

elif [ condition2 ]<br />

# Same as else if<br />

then<br />

command4<br />

command5<br />

else<br />

default−command<br />

fi<br />

The if test condition−true construct is the exact equivalent of if [ condition−true ]. As<br />

it happens, the left bracket, [ , is a token which invokes the test command. The closing right bracket, ] , in an<br />

if/test should not therefore be strictly necessary, however newer versions of Bash require it.<br />

The test command is a Bash builtin which tests file types and compares strings. Therefore, in a Bash<br />

script, test does not call the external /usr/bin/test binary, which is part of the sh−utils package.<br />

Likewise, [ does not call /usr/bin/[, which is linked to /usr/bin/test.<br />

bash$ type test<br />

test is a shell builtin<br />

bash$ type '['<br />

[ is a shell builtin<br />

bash$ type '[['<br />

[[ is a shell keyword<br />

bash$ type ']]'<br />

]] is a shell keyword<br />

bash$ type ']'<br />

bash: type: ]: not found<br />

Chapter 7. Tests 43

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!