- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why should eval be avoided in Bash, and what should I use instead?
eval is a builtin command of the Bash shell which concatenates its arguments into a single string. Then it joins the arguments with spaces, then executes that string as a bash command. Below is an example of how it works.
eval example
In the below example we take a string which has some Unix commands built into it and then apply eval to it.
$ var="echo n" $ echo $var $ eval $var
Running the above code gives us the following result −
echo n n
As you can see, when eval is applied the variable expands it gets executed as a command and no longer behaves as just a string.
Problem with eval
When we create some variables or scripts containing functions, we can push some values to the variables or functions which can be potentially dangerous. For example a remove file command can be passed to a script which accepts user arguments. The owner of the script will have delete file privilege but the user who is calling the script does not have.
Consider the below script in which we are calling a function which has a eval function inside it.
Printa_rray() { in_array=$1 eval echo "\"The first vale in the array is \${$in_array[0]}\"" } fruits=(apple, orange, grapes,berry) print_array fruits
Running the above code gives us the following result −
The first vale in the array is apple.
The above result is expected. But imagine a user calls the function using the below parameter.
print_array() { in_array=$1 eval echo "\"The first vale in the array is \${$in_array[0]}\"" } fruits=(apple, orange, grapes,berry) print_array 'x}"; cal; #'
Running the above code gives us the following result −
The first vale in the array is December 2019 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
As you can see, because of the eval function present in the script, the use is able to completely bypass the intended functionality of the acript. This can turn dangerous if the user passes commands like rm *.* as the acript argument.
eval alternatives
Because of above implications, there are some eval alternative available which can be used which will not pose such security threats.
use token_quote to male eval safer.