How to Use the eval Command in Linux Bash

Yahya Irmak Feb 02, 2024
  1. Use the eval Command in Bash
  2. Be Cautious When Using eval in Bash
How to Use the eval Command in Linux Bash

This article shows how to use the eval command in Linux Bash. Then, we will address the vulnerability that this command can cause.

Use the eval Command in Bash

The eval command interprets the given arguments as a Bash command.

Let’s take an example to understand better. We have a file, test.txt, containing This is how eval works!.

Below is the content of the example Bash script.

x="cat test.txt"
echo "The value of the variable x: "
echo $x

echo "The result when we use eval command:"
eval $x

First, we print the variable x with echo. This is exactly the value we defined.

Then, we use the eval command with the variable we defined. This time, the content of the variable is executed as a command, and the contents of test.txt get printed.

bash eval command

Be Cautious When Using eval in Bash

The eval command is evil. Be careful when using this command.

Consider the following example of a simple Bash script that calculates the given expression and prints the result to the screen. Since the eval will execute the given input as a Bash command, this will also execute if the user provides a malicious command as an input.

read -p "Enter the expression to calculate (2 + 3) " expression
result="expr $expression"
eval $result

Eval is evil command

Author: Yahya Irmak
Yahya Irmak avatar Yahya Irmak avatar

Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.

LinkedIn

Related Article - Bash Eval