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

#+ declared and set within the function.<br />

}<br />

original_array=( element1 element2 element3 element4 element5 )<br />

echo<br />

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

# List all elements of original array.<br />

# This is the trick that permits passing an array to a function.<br />

# **********************************<br />

argument=`echo ${original_array[@]}`<br />

# **********************************<br />

# Pack a variable<br />

#+ with all the space−separated elements of the original array.<br />

#<br />

# Note that attempting to just pass the array itself will not work.<br />

# This is the trick that allows grabbing an array as a "return value".<br />

# *****************************************<br />

returned_array=( `Pass_Array "$argument"` )<br />

# *****************************************<br />

# Assign 'echoed' output of function to array variable.<br />

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

echo "============================================================="<br />

# Now, try it again,<br />

#+ attempting to access (list) the array from outside the function.<br />

Pass_Array "$argument"<br />

# The function itself lists the array, but...<br />

#+ accessing the array from outside the function is forbidden.<br />

echo "Passed array (within function) = ${passed_array[@]}"<br />

# NULL VALUE since this is a variable local to the function.<br />

echo<br />

exit 0<br />

For a more elaborate example of passing arrays to functions, see Example A−11.<br />

• Using the double parentheses construct, it is possible to use C−like syntax for setting and<br />

incrementing variables and in for and while loops. See Example 10−12 and Example 10−17.<br />

• A useful scripting technique is to repeatedly feed the output of a filter (by piping) back to the same<br />

filter, but with a different set of arguments and/or options. Especially suitable for this are tr and grep.<br />

# From "wstrings.sh" example.<br />

wlist=`strings "$1" | tr A−Z a−z | tr '[:space:]' Z | \<br />

tr −cs '[:alpha:]' Z | tr −s '\173−\377' Z | tr Z ' '`<br />

Example 34−13. Fun with anagrams<br />

#!/bin/bash<br />

Chapter 34. Miscellany 352

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

Saved successfully!

Ooh no, something went wrong!