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

exit 0<br />

bash$ echo $WHATEVER<br />

bash$<br />

Sure enough, back at the command prompt, $WHATEVER remains unset.<br />

Setting and manipulating variables in a subshell, then attempting to use those same variables outside the scope<br />

of the subshell will result an unpleasant surprise.<br />

Example 32−1. Subshell Pitfalls<br />

#!/bin/bash<br />

# Pitfalls of variables in a subshell.<br />

outer_variable=outer<br />

echo<br />

echo "outer_variable = $outer_variable"<br />

echo<br />

(<br />

# Begin subshell<br />

echo "outer_variable inside subshell = $outer_variable"<br />

inner_variable=inner # Set<br />

echo "inner_variable inside subshell = $inner_variable"<br />

outer_variable=inner # Will value change globally?<br />

echo "outer_variable inside subshell = $outer_variable"<br />

# End subshell<br />

)<br />

echo<br />

echo "inner_variable outside subshell = $inner_variable" # Unset.<br />

echo "outer_variable outside subshell = $outer_variable" # Unchanged.<br />

echo<br />

exit 0<br />

Piping echooutput to a read may produce unexpected results. In this scenario, the read acts as if it were<br />

running in a subshell. Instead, use the set command (as in Example 11−14).<br />

Example 32−2. Piping the output of echo to a read<br />

#!/bin/bash<br />

# badread.sh:<br />

# Attempting to use 'echo and 'read'<br />

#+ to assign variables non−interactively.<br />

a=aaa<br />

b=bbb<br />

c=ccc<br />

Chapter 32. Gotchas 330

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

Saved successfully!

Ooh no, something went wrong!