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.
#!/bin/bash
# Yet another version of the "column totaler" script (col-totaler.sh)
#+ 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.
ARGS=2
E_WRONGARGS=85
if [ $# -ne "$ARGS" ] # Check for proper number of command-line args.
then
echo "Usage: `basename $0` filename column-number"
exit $E_WRONGARGS
fi
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
1) Original Statement:
TOTAL= 'expr $FLIGHT + $GROUND'

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

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

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

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