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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

# grep PATTERN /etc/passwd | awk −F":" '{ print $5 }'<br />

# or<br />

# awk −F: '/PATTERN/ {print $5}'<br />

# or<br />

# awk −F: '($1 == "username") { print $5 }' # real name from username<br />

# However, it might not be as instructive.<br />

exit 0<br />

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

There is an alternative, and perhaps less confusing method of redirecting a function's stdin. This<br />

involves redirecting the stdin to an embedded bracketed code block within the function.<br />

# Instead of:<br />

Function ()<br />

{<br />

...<br />

} < file<br />

# Try this:<br />

Function ()<br />

{<br />

{<br />

...<br />

} < file<br />

}<br />

# Similarly,<br />

Function () # This works.<br />

{<br />

{<br />

echo $*<br />

} | tr a b<br />

}<br />

Function () # This doesn't work.<br />

{<br />

echo $*<br />

} | tr a b # A nested code block is mandatory here.<br />

# Thanks, S.C.<br />

23.2. Local Variables<br />

What makes a variable "local"?<br />

local variables<br />

A variable declared as local is one that is visible only within the block of code in which it appears. It<br />

has local "scope". In a function, a local variable has meaning only within that function block.<br />

Example 23−8. Local variable visibility<br />

#!/bin/bash<br />

func ()<br />

Chapter 23. Functions 283

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

Saved successfully!

Ooh no, something went wrong!