8.10 eval: When You Need Another ChanceIf you read the previous article (8.9 ) , you saw that, most of the time, the shell evaluates the command line "in the right order." But what about when it doesn't? Here's a situation that the shell can't handle. It's admittedly contrived, but not too different from what you might find in a shell program (1.5 ) : % When we use the variable But there's a loophole. The eval command says, in essence, "Give me another chance. Re-evaluate this line and execute it." Here's what happens if we stick eval before the echo : % The shell converts Here's a more realistic example; you see code like this fairly often in Bourne shell scripts: ... command='grep $grepopts $searchstring $file' for opt do case "$opt" in file) output=' > $ofile' ;; read) output=' | more' ;; sort) postproc=' | sort $sortopts';; esac done ... eval $command $postproc $output Do you see what's happening? We're constructing a command that will look something like: grep $grepopts $searchstring $file | sort $sortopts > $ofile But the entire command is "hidden" in shell variables, including the
I/O redirectors and various options. If the eval
isn't there,
this command will blow up in all sorts of bizarre ways. You'll see
messages like eval is incredibly useful if you have shell variables that include other shell variables, shell variables that include aliases, shell variables that include I/O redirectors, or all sorts of perversities. It's commonly used within shell scripts to "evaluate" commands that are built during execution. There are more examples of eval in articles 5.4 , 10.7 , 10.10 , 45.17 , 45.34 , 46.3 , and others. - |
|