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.

The 0 − 255 range for function return values is a severe limitation. Global variables and other<br />

workarounds are often problematic. An alternative method for a function to communicate a value<br />

back to the main body of the script is to have the function write to stdout the "return value", and<br />

assign this to a variable.<br />

Example 34−10. Return value trickery<br />

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

#!/bin/bash<br />

# multiplication.sh<br />

multiply ()<br />

# Multiplies params passed.<br />

{ # Will accept a variable number of args.<br />

local product=1<br />

until [ −z "$1" ]<br />

do<br />

let "product *= $1"<br />

shift<br />

done<br />

# Until uses up arguments passed...<br />

echo $product<br />

# Will not echo to stdout,<br />

} #+ since this will be assigned to a variable.<br />

mult1=15383; mult2=25211<br />

val1=`multiply $mult1 $mult2`<br />

echo "$mult1 X $mult2 = $val1"<br />

# 387820813<br />

mult1=25; mult2=5; mult3=20<br />

val2=`multiply $mult1 $mult2 $mult3`<br />

echo "$mult1 X $mult2 X $mult3 = $val2"<br />

# 2500<br />

mult1=188; mult2=37; mult3=25; mult4=47<br />

val3=`multiply $mult1 $mult2 $mult3 $mult4`<br />

echo "$mult1 X $mult2 X $mult3 X mult4 = $val3"<br />

# 8173300<br />

exit 0<br />

The same technique also works for alphanumeric strings. This means that a function can "return" a<br />

non−numeric value.<br />

capitalize_ichar ()<br />

# Capitalizes initial character<br />

{ #+ of argument string(s) passed.<br />

string0="$@"<br />

firstchar=${string0:0:1}<br />

string1=${string0:1}<br />

# Accepts multiple arguments.<br />

# First character.<br />

# Rest of string(s).<br />

FirstChar=`echo "$firstchar" | tr a−z A−Z`<br />

# Capitalize first character.<br />

echo "$FirstChar$string1" # Output to stdout.<br />

}<br />

Chapter 34. Miscellany 350

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

Saved successfully!

Ooh no, something went wrong!