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

# Something like this might be useful in some contexts.<br />

NO_EXIT=1 # Will enable function definition below.<br />

[[ $NO_EXIT −eq 1 ]] && exit() { true; } # Function definition in an "and−list".<br />

# If $NO_EXIT is 1, declares "exit ()".<br />

# This disables the "exit" builtin by aliasing it to "true".<br />

exit # Invokes "exit ()" function, not "exit" builtin.<br />

# Thanks, S.C.<br />

23.1. Complex Functions and Function Complexities<br />

Functions may process arguments passed to them and return an exit status to the script for further processing.<br />

function_name $arg1 $arg2<br />

The function refers to the passed arguments by position (as if they were positional parameters), that is, $1,<br />

$2, and so forth.<br />

Example 23−2. Function Taking Parameters<br />

#!/bin/bash<br />

# Functions and parameters<br />

DEFAULT=default<br />

# Default param value.<br />

func2 () {<br />

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

# Is parameter #1 zero length?<br />

then<br />

echo "−Parameter #1 is zero length.−" # Or no parameter passed.<br />

else<br />

echo "−Param #1 is \"$1\".−"<br />

fi<br />

variable=${1−$DEFAULT}<br />

echo "variable = $variable"<br />

# What does<br />

#+ parameter substitution show?<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

# It distinguishes between<br />

#+ no param and a null param.<br />

if [ "$2" ]<br />

then<br />

echo "−Parameter #2 is \"$2\".−"<br />

fi<br />

}<br />

return 0<br />

echo<br />

echo "Nothing passed."<br />

func2<br />

echo<br />

# Called with no params<br />

Chapter 23. Functions 276

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

Saved successfully!

Ooh no, something went wrong!