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.

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

Notice that a buffer overrun does not occur. This is one instance where an interpreted language, such as<br />

Bash, provides more protection from programmer mistakes than a compiled language.<br />

Command substitution permits setting a variable to the output of a loop. The key to this is grabbing the output<br />

of an echo command within the loop.<br />

Example 14−2. Generating a variable from a loop<br />

#!/bin/bash<br />

# csubloop.sh: Setting a variable to the output of a loop.<br />

variable1=`for i in 1 2 3 4 5<br />

do<br />

echo −n "$i"<br />

done`<br />

# The 'echo' command is critical<br />

#+ to command substitution.<br />

echo "variable1 = $variable1" # variable1 = 12345<br />

i=0<br />

variable2=`while [ "$i" −lt 10 ]<br />

do<br />

echo −n "$i"<br />

# Again, the necessary 'echo'.<br />

let "i += 1"<br />

# Increment.<br />

done`<br />

echo "variable2 = $variable2" # variable2 = 0123456789<br />

exit 0<br />

Command substitution makes it possible to extend the toolset available to Bash. It is simply a matter of<br />

writing a program or script that outputs to stdout (like a well−behaved UNIX tool should) and assigning<br />

that output to a variable.<br />

#include <br />

/* "Hello, world." C program */<br />

int main()<br />

{<br />

printf( "Hello, world." );<br />

return (0);<br />

}<br />

bash$ gcc −o hello hello.c<br />

#!/bin/bash<br />

# hello.sh<br />

greeting=`./hello`<br />

echo $greeting<br />

Chapter 14. Command Substitution 239

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

Saved successfully!

Ooh no, something went wrong!