Eval Command in Linux

Today let’s see Eval Command in Linux. It is a built-in Unix command – it’s used to execute arguments as shell commands. It’s useful when you have a command stored in a variable and you want to execute it.

Syntax

[root@justgeek]# eval [arg ...]
[root@justgeek]# mycommand="ls -ltr"

[root@justgeek]# echo $mycommand
ls -ltr

[root@justgeek]# eval $mycommand
total 0
-rw-r--r-- 1 root root 0 Nov  5 07:40 file1.txt
-rw-r--r-- 1 root root 0 Nov  5 07:40 file3.txt
-rw-r--r-- 1 root root 0 Nov  5 07:40 file2.txt

Look at the example above, I have stored the command ls - ltr in the variable mycommand so when I do echo it just prints what is in the variable. But when I do Eval followed with the variable – it will actually execute the command.

Eval is a powerful command but it’s Evil – it has security issues. let me explain why.

Just imagine someone puts a script on your server with the rm command – Eval command will delete it all. So that’s the reason Eval Command in Linux is powerful but evil sometimes. You can find more details about it here

Example of Eval as Evil.
Consider you wrote a script, which asks users for their birth year and it calculates their age. What could possibly go wrong? Let’s see.

read -p "Enter your birth year to calculate your age : " birthyear
currentyear=$(date +"%Y")
result="expr $currentyear - $birthyear"
eval $result
Eval Command in Linux
For better readability of the script above, I have added it as an image as well 🙂

An innocent user ran the script above, entered his birth year and he got the results as expected. See the results below.

[root@justgeek ~]$ ./age-calculator
Enter your birth year to calculate your age : 1995
27

But it’s not as simple as it looks. But there was a hacker, he used this to get the vital information of the server. He passed cat /etc/passwd along with the birth year and see what happened.

[root@justgeek ~]$ ./age-calculator
Enter your birth year to calculate your age : 1995 ; cat /etc/passwd
27
root:x:0:0:root:/root:/bin/bash
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt

It has displayed, the contents of /etc/passwd along with the output. This is the reason people call Eval Evil.

I am trying to cover whole Linux Commands hopefully I will get there someday. You can suggest what next can be covered in the comment section.

Leave a Comment