Shell Variables   «Prev 

Embedded Command Execution

A shell script may act as an embedded command inside another shell script, a Tcl or wish script, or even a Makefile. It can be invoked as an external shell command in a C program using the
system() call, i.e., system("script_name");.

Setting a variable to the contents of an embedded sed or awk script increases the readability of the surrounding shell wrapper.
# Yet another version of the "column totaler" script (
#+ that adds up a specified column (of numbers) in the target file.
# This uses the environment to pass a script variable to 'awk' . . .
#+ and places the awk script in a variable.
if [ $# -ne "$ARGS" ] # Check for proper number of command-line args.
echo "Usage: `basename $0` filename column-number"
filename=$1 column_number=$2
#===== Same as original script, up to this point =====#
export column_number # Export column number to environment, so it's available for retrieval.
# ----------------------------------------------- awkscript='{ total += $ENVIRON["column_number"] } END { print total }' # Yes, a variable can hold an awk script. # -----------------------------------------------
# Now, run the awk script. awk "$awkscript" "$filename" # Thanks, Stephane Chazelas. exit 0

Using export to pass a variable to an embedded awk script
1) Original Statement:

2) Value of $FLIGHT is inserted
TOTAL= 'expr 190 + $GROUND'

3) Value of $GROUND is inserted
TOTAL= 'expr 190 + 45'

4) Embedded command is executed.
TOTAL= 'expr 190 + 45'

5) Result of Embedded Command is inserted and assigned as the value of TOTAL.
TOTAL =235