Eval Command in Linux/Unix With Examples | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

eval is a built-in Linux command which is used to execute arguments as a shell command. It combines arguments into a single string and uses it as an input to the shell and execute the commands.

eval command comes in handy when you have a unix or linux command stored in a variable and you want to execute that command stored in the string. The eval command first evaluates the argument and then runs the command stored in the argument.

~/codeFactory$ eval --help
eval: eval [arg ...]
    Execute arguments as a shell command.
    
    Combine ARGs into a single string, use the result as input to the shell,
    and execute the resulting commands.
    
    Exit Status:
    Returns exit status of command or success if command is null.

Example 1: To execute that command stored in the string

~/codeFactory$ COMMAND="cd Download"
~/codeFactory$ eval $COMMAND
~/codeFactory/Download$ 

Example 2:

~/codeFactory$ cat evaltest.sh 
foo=10 x=foo
y='$'$x
echo $y
eval y='$'$x
echo $y

~/codeFactory$ sh evaltest.sh 
$foo
10

It will take an argument and construct a command of it, which will be executed by the shell.

1) foo=10 x=foo
2) y='$'$x
3) echo $y
4) $foo
5) eval y='$'$x
6) echo $y
7) 10


1. In the first line you define $foo with the value '10' and $x with the value 'foo'.
2. Now define $y, which consists of the string '$foo'. The dollar sign must be escaped with '$'.
3. To check the result, echo $y.
4. The result will be the string '$foo'
5. Now we repeat the assignment with eval. It will first evaluate $x to the string 'foo'. Now we have the statement y=$foo which will get evaluated to y=10.
6. The result of echo $y is now the value '10'.

Leave a comment