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

exit 0<br />

See also Example 10−28.<br />

The largest positive integer a function can return is 256. The return command is closely tied to<br />

the concept of exit status, which accounts for this particular limitation. Fortunately, there are<br />

various workarounds for those situations requiring a large integer return value from a function.<br />

Example 23−5. Testing large return values in a function<br />

#!/bin/bash<br />

# return−test.sh<br />

# The largest positive value a function can return is 256.<br />

return_test ()<br />

{<br />

return $1<br />

}<br />

# Returns whatever passed to it.<br />

return_test 27<br />

# o.k.<br />

echo $? # Returns 27.<br />

return_test 256 # Still o.k.<br />

echo $? # Returns 256.<br />

return_test 257<br />

echo $?<br />

# Error!<br />

# Returns 1 (return code for miscellaneous error).<br />

return_test −151896 # However, large negative numbers work.<br />

echo $? # Returns −151896.<br />

exit 0<br />

As we have seen, a function can return a large negative value. This also permits returning large<br />

positive integer, using a bit of trickery.<br />

An alternate method of accomplishing this is to simply assign the "return value" to a global<br />

variable.<br />

Return_Val=<br />

# Global variable to hold oversize return value of function.<br />

alt_return_test ()<br />

{<br />

fvar=$1<br />

Return_Val=$fvar<br />

return # Returns 0 (success).<br />

}<br />

alt_return_test 1<br />

echo $? # 0<br />

echo "return value = $Return_Val" # 1<br />

Chapter 23. Functions 280

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

Saved successfully!

Ooh no, something went wrong!