The eval Command

The eval command reads and executes commands using the following format:

					eval
					commands
				

It causes commands to be expanded twice. For simple commands, there is no difference in execution with or without eval:

					$ eval print ∼
					/home/anatole
				

Here is a more complicated command that illustrates the use of eval. We want the contents of the stext file redirected when variable X is accessed.

					$ cat stext
					She sells seashells by the seashore.
				

First, variable X is set to "<stext":

					$ X="<stext"
				

When the value of X is printed using simple variable expansion, it generates an error:

					$ cat $X
					<stext: No such file or directory
				

Using the eval command, X is first expanded to <stext, then the command cat <stext is executed. This causes the contents of stext to be displayed:

					$ eval cat $X
					She sells seashells by the seashore.
				

In this Korn shell script, the eval command is used to display the last command-line argument:

					$ cat eval_test
					print "Total command-line arguments is $#"
					print "The last argument is $$#"
				

What you want is $# to be expanded first to the number of arguments, then $n to be expanded to the value of the last argument. Without the eval command, this is the output of eval_test:

					$ eval_test a b c
					Total command-line arguments is 3
					The last argument is 581#
				

The output 581# is generated because $$ is first expanded to the process id. Using the eval command to expand the print command twice, we get the correct result.

					$ cat eval_test
					print "Total command-line arguments is $#"
					print "The last argument is $(eval print $$#)"
					$ eval_test1 a b c
					The number of command-line arguments is 3
					The last argument is c
				

The is needed so that the $ character is ignored on the first expansion. After the first expansion, the $(eval print $$#) command becomes $(print $3). This is then expanded to c.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.37.196