Book Image

Linux Shell Scripting Essentials

Book Image

Linux Shell Scripting Essentials

Overview of this book

Table of Contents (15 chapters)
Linux Shell Scripting Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Construct commands using eval


The eval command is a shell builtin command used to construct a command by concatenating arguments passed to eval. A concatenated command is further executed by shell and returns a result. If no arguments are given to eval, it returns 0.

The syntax of the eval command is as follows:

eval [arg …]

The following example shows the expansion of a variable to the name of another variable using eval:

$ name=foo
$ foo="Welcome to foo world"
$ echo $name
foo
$ new_name='$'$name    #new_name just stores string value $foo
$ echo $new_name
$foo
$ eval new_name='$'$name  # eval processes $foo string into variable and  prints                 # foo variable value
Welcome to foo world

Another example where eval can be useful is as follows:

$ pipe="|"
$  df $pipe wc  # Will give error because 
df: '|': No such file or directory
df: 'wc': No such file or directory
$ eval df $pipe wc  # eval executes it as shell command
12      73     705

Here, the df command shows a system disk's usage:

A shell script showing the use of eval is as follows:
#!/bin/bash
#Filename: eval.sh
#Description: Evaluating string as a command using eval

cmd="ls /usr"
echo "Output of command $cmd -"
eval $cmd   #eval will treat content of cmd as shell command and execute it
cmd1="ls /usr | wc -l"
echo "Line count of /usr -"
eval $cmd1

expression="expr 2 + 4 \* 6"
echo "Value of $expression"
eval $expression

Running the script will give you the following result:

Output of command ls /usr -
avr  bin  games  include  lib  lib64  libexec  local  sbin  share  src  tmp
Line count of /usr -
12
Value of expr 2 + 4 \* 6
26