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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

echo "Zero−length parameter passed."<br />

func2 ""<br />

# Called with zero−length param<br />

echo<br />

echo "Null parameter passed."<br />

func2 "$uninitialized_param"<br />

echo<br />

# Called with uninitialized param<br />

echo "One parameter passed."<br />

func2 first<br />

# Called with one param<br />

echo<br />

echo "Two parameters passed."<br />

func2 first second # Called with two params<br />

echo<br />

echo "\"\" \"second\" passed."<br />

func2 "" second # Called with zero−length first parameter<br />

echo<br />

# and ASCII string as a second one.<br />

exit 0<br />

The shift command works on arguments passed to functions (see Example 34−10).<br />

In contrast to certain other programming languages, shell scripts normally pass only value parameters to<br />

functions. [51] Variable names (which are actually pointers), if passed as parameters to functions, will be<br />

treated as string literals and cannot be dereferenced. Functions interpret their arguments literally.<br />

Exit and Return<br />

exit status<br />

Functions return a value, called an exit status. The exit status may be explicitly specified by a return<br />

statement, otherwise it is the exit status of the last command in the function (0 if successful, and a<br />

non−zero error code if not). This exit status may be used in the script by referencing it as $?. This<br />

mechanism effectively permits script functions to have a "return value" similar to C functions.<br />

return<br />

Terminates a function. A return command [52] optionally takes an integer argument, which is<br />

returned to the calling script as the "exit status" of the function, and this exit status is assigned to the<br />

variable $?.<br />

Example 23−3. Maximum of two numbers<br />

#!/bin/bash<br />

# max.sh: Maximum of two integers.<br />

E_PARAM_ERR=−198<br />

EQUAL=−199<br />

# If less than 2 params passed to function.<br />

# Return value if both params equal.<br />

max2 ()<br />

# Returns larger of two numbers.<br />

{ # Note: numbers compared must be less than 257.<br />

if [ −z "$2" ]<br />

then<br />

return $E_PARAM_ERR<br />

Chapter 23. Functions 277

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

Saved successfully!

Ooh no, something went wrong!