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.

if [[ −e $file ]]<br />

then<br />

echo "Password file exists."<br />

fi<br />

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

Using the [[ ... ]] test construct, rather than [ ... ] can prevent many logic errors in scripts. For example,<br />

the &&, ||, operators work within a [[ ]] test, despite giving an error within a [ ] construct.<br />

Following an if, neither the test command nor the test brackets ( [ ] or [[ ]] ) are strictly<br />

necessary.<br />

dir=/home/bozo<br />

if cd "$dir" 2>/dev/null; then<br />

echo "Now in $dir."<br />

else<br />

echo "Can't change to $dir."<br />

fi<br />

# "2>/dev/null" hides error message.<br />

The "if COMMAND" construct returns the exit status of COMMAND.<br />

Similarly, a condition within test brackets may stand alone without an if, when used in<br />

combination with a list construct.<br />

var1=20<br />

var2=22<br />

[ "$var1" −ne "$var2" ] && echo "$var1 is not equal to $var2"<br />

home=/home/bozo<br />

[ −d "$home" ] || echo "$home directory does not exist."<br />

The (( )) construct expands and evaluates an arithmetic expression. If the expression evaluates as zero, it<br />

returns an exit status of 1, or "false". A non−zero expression returns an exit status of 0, or "true". This is in<br />

marked contrast to using the test and [ ] constructs previously discussed.<br />

Example 7−3. Arithmetic Tests using (( ))<br />

#!/bin/bash<br />

# Arithmetic tests.<br />

# The (( ... )) construct evaluates and tests numerical expressions.<br />

# Exit status opposite from [ ... ] construct!<br />

(( 0 ))<br />

echo "Exit status of \"(( 0 ))\" is $?." # 1<br />

(( 1 ))<br />

echo "Exit status of \"(( 1 ))\" is $?." # 0<br />

(( 5 > 4 )) # true<br />

echo "Exit status of \"(( 5 > 4 ))\" is $?." # 0<br />

(( 5 > 9 )) # false<br />

echo "Exit status of \"(( 5 > 9 ))\" is $?." # 1<br />

Chapter 7. Tests 45

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

Saved successfully!

Ooh no, something went wrong!