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

The export command makes available variables to all child processes of the running script or shell.<br />

Unfortunately, there is no way to export variables back to the parent process, to the process that<br />

called or invoked the script or shell. One important use of export command is in startup files, to<br />

initialize and make accessible environmental variables to subsequent user processes.<br />

Example 11−16. Using export to pass a variable to an embedded awk script<br />

#!/bin/bash<br />

# Yet another version of the "column totaler" script (col−totaler.sh)<br />

# that adds up a specified column (of numbers) in the target file.<br />

# This uses the environment to pass a script variable to 'awk'.<br />

ARGS=2<br />

E_WRONGARGS=65<br />

if [ $# −ne "$ARGS" ] # Check for proper no. of command line args.<br />

then<br />

echo "Usage: `basename $0` filename column−number"<br />

exit $E_WRONGARGS<br />

fi<br />

filename=$1<br />

column_number=$2<br />

#===== Same as original script, up to this point =====#<br />

export column_number<br />

# Export column number to environment, so it's available for retrieval.<br />

# Begin awk script.<br />

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

awk '{ total += $ENVIRON["column_number"]<br />

}<br />

END { print total }' $filename<br />

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

# End awk script.<br />

# Thanks, Stephane Chazelas.<br />

exit 0<br />

It is possible to initialize and export variables in the same operation, as in export<br />

var1=xxx.<br />

However, as Greg Keraunen points out, in certain situations this may have a different<br />

effect than setting a variable, then exporting it.<br />

bash$ export var=(a b); echo ${var[0]}<br />

(a b)<br />

bash$ var=(a b); export var; echo ${var[0]}<br />

a<br />

Chapter 11. Internal Commands and Builtins 137

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

Saved successfully!

Ooh no, something went wrong!