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

• newstring=`capitalize_ichar "each sentence should start with a capital letter."`<br />

echo "$newstring"<br />

# Each sentence should start with a capital letter.<br />

It is even possible for a function to "return" multiple values with this method.<br />

Example 34−11. Even more return value trickery<br />

#!/bin/bash<br />

# sum−product.sh<br />

# A function may "return" more than one value.<br />

sum_and_product () # Calculates both sum and product of passed args.<br />

{<br />

echo $(( $1 + $2 )) $(( $1 * $2 ))<br />

# Echoes to stdout each calculated value, separated by space.<br />

}<br />

echo<br />

echo "Enter first number "<br />

read first<br />

echo<br />

echo "Enter second number "<br />

read second<br />

echo<br />

retval=`sum_and_product $first $second` # Assigns output of function.<br />

sum=`echo "$retval" | awk '{print $1}'` # Assigns first field.<br />

product=`echo "$retval" | awk '{print $2}'` # Assigns second field.<br />

echo "$first + $second = $sum"<br />

echo "$first * $second = $product"<br />

echo<br />

exit 0<br />

• Next in our bag of trick are techniques for passing an array to a function, then "returning" an array<br />

back to the main body of the script.<br />

Passing an array involves loading the space−separated elements of the array into a variable with<br />

command substitution. Getting an array back as the "return value" from a function uses the previously<br />

mentioned strategem of echoing the array in the function, then invoking command substitution and<br />

the ( ... ) operator to assign it to an array.<br />

Example 34−12. Passing and returning arrays<br />

#!/bin/bash<br />

# array−function.sh: Passing an array to a function and...<br />

# "returning" an array from a function<br />

Pass_Array ()<br />

{<br />

local passed_array # Local variable.<br />

passed_array=( `echo "$1"` )<br />

echo "${passed_array[@]}"<br />

# List all the elements of the new array<br />

Chapter 34. Miscellany 351

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

Saved successfully!

Ooh no, something went wrong!