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 />

echo "uninitialized_var = $uninitialized_var"<br />

# uninitialized_var =<br />

Mixing up = and −eq in a test. Remember, = is for comparing literal variables and −eq for integers.<br />

if [ "$a" = 273 ]<br />

if [ "$a" −eq 273 ]<br />

# Is $a an integer or string?<br />

# If $a is an integer.<br />

# Sometimes you can mix up −eq and = without adverse consequences.<br />

# However...<br />

a=273.0<br />

# Not an integer.<br />

if [ "$a" = 273 ]<br />

then<br />

echo "Comparison works."<br />

else<br />

echo "Comparison does not work."<br />

fi # Comparison does not work.<br />

# Same with a=" 273" and a="0273".<br />

# Likewise, problems trying to use "−eq" with non−integer values.<br />

if [ "$a" −eq 273.0 ]<br />

then<br />

echo "a = $a'<br />

fi # Aborts with an error message.<br />

# test.sh: [: 273.0: integer expression expected<br />

Mixing up integer and string comparison operators.<br />

#!/bin/bash<br />

# bad−op.sh<br />

number=1<br />

while [ "$number" < 5 ] # Wrong! Should be while [ "number" −lt 5 ]<br />

do<br />

echo −n "$number "<br />

let "number += 1"<br />

done<br />

# Attempt to run this bombs with the error message:<br />

# bad−op.sh: 5: No such file or directory<br />

Sometimes variables within "test" brackets ([ ]) need to be quoted (double quotes). Failure to do so may cause<br />

unexpected behavior. See Example 7−6, Example 16−4, and Example 9−6.<br />

Commands issued from a script may fail to execute because the script owner lacks execute permission for<br />

them. If a user cannot invoke a command from the command line, then putting it into a script will likewise<br />

fail. Try changing the attributes of the command in question, perhaps even setting the suid bit (as root, of<br />

course).<br />

Attempting to use − as a redirection operator (which it is not) will usually result in an unpleasant surprise.<br />

Chapter 32. Gotchas 328

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

Saved successfully!

Ooh no, something went wrong!