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.

Example 11−11. A version of "rot13"<br />

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

#!/bin/bash<br />

# A version of "rot13" using 'eval'.<br />

# Compare to "rot13.sh" example.<br />

setvar_rot_13()<br />

# "rot13" scrambling<br />

{<br />

local varname=$1 varvalue=$2<br />

eval $varname='$(echo "$varvalue" | tr a−z n−za−m)'<br />

}<br />

setvar_rot_13 var "foobar"<br />

echo $var<br />

echo $var | tr a−z n−za−m<br />

# Run "foobar" through rot13.<br />

# sbbone<br />

# foobar<br />

# Back to original variable.<br />

# This example by Stephane Chazelas.<br />

exit 0<br />

Rory Winston contributed the following instance of how useful eval can be.<br />

Example 11−12. Using eval to force variable substitution in a Perl script<br />

In the Perl script "test.pl":<br />

...<br />

my $WEBROOT = ;<br />

...<br />

To force variable substitution try:<br />

$export WEBROOT_PATH=/usr/local/webroot<br />

$sed 's//$WEBROOT_PATH/' < test.pl > out<br />

But this just gives:<br />

my $WEBROOT = $WEBROOT_PATH;<br />

However:<br />

$export WEBROOT_PATH=/usr/local/webroot<br />

$eval sed 's//$WEBROOT_PATH/' < test.pl > out<br />

# ====<br />

That works fine, and gives the expected substitution:<br />

my $WEBROOT = /usr/local/webroot<br />

set<br />

The eval command can be risky, and normally should be avoided when there exists a<br />

reasonable alternative. An eval $COMMANDS executes the contents of COMMANDS,<br />

which may contain such unpleasant surprises as rm −rf *. Running an eval on<br />

unfamiliar code written by persons unknown is living dangerously.<br />

The set command changes the value of internal script variables. One use for this is to toggle option<br />

flags which help determine the behavior of the script. Another application for it is to reset the<br />

positional parameters that a script sees as the result of a command (set `command`). The script<br />

can then parse the fields of the command output.<br />

Chapter 11. Internal Commands and Builtins 134

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

Saved successfully!

Ooh no, something went wrong!