Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • 1. Syntax
  • 2. Execute commands using eval
  • 3. Set variables in shell
  • 4. Substitute variables inside a string
  • 5. Access Variables within Variables
  • 6. What happens if eval is not used carefully?
  • 7. Example
  • Conclusion

Bash eval Command with Examples

PreviousBash Scripting: How to Check if Directory ExistsNextHow to Use Sleep Command in Bash Scripting

Last updated 1 year ago

The eval command is an extremely powerful tool and can be used with a lot of flexibility. It joins the arguments and executes the generated string as a Bash command. Eval executes the command in the current shell environment. In this tutorial, we will deal with different use cases of the eval command. We will also discuss the security concerns associated with it.

1. Syntax

The eval is a built-in Linux command line utility, accepting a string as its argument and evaluating it, then executing the stored command present in the argument.

Syntax:

eval [argument]

The command takes the argument and converts it as a single string. This then acts as an input to another child process of the shell. This is where the resulting commands eventually get executed.

2. Execute commands using eval

The eval command is widely used to execute commands.

Example:

var1="echo"var2="Hello"eval $var1 $var2

We have two variables with assigned values. With eval, we join the arguments and execute them as a single string, separated by a single space. In our case, we concatenated the value of the variables, making it "echo Hello" and then ran that string as a command, "echo Hello". The command executes in the current shell.

3. Set variables in shell

It is a very common practice to store all the variables the script needs, stored in some file.

Let us assume we have a properties file, say shell.properties, as follows:

varA=1varB=2varC=3

Example:

#!/bin/bash eval "$(cat shell.properties)" echo variable 1 is $varAecho variable 2 is $varBecho variable 3 is $varCadd=`expr $varA + $varB + $varC`echo sum is is $add

During the script execution, we use the file, storing the variables to set the environment of the current shell with those variables with the help of the eval command. In this example, we have a shell.properties file with three variables varA, varB, and var3 holding the values 1, 2, and 3 respectively.

Upon the execution of the eval command, these variables now become available to the current shell and hence, to our script as well. This makes varA=1, varB=2 and varC=3. Once we have the variables, we can perform any Bash operation on these variables, for instance add in this case.

4. Substitute variables inside a string

With eval command, we can carry out variable expansions in strings. We can also replace the Bash variables by their actual values.

Example:

str="User $USER is currently in the $PWD path."eval echo $strecho $str > evalExample.txtcat evalExample.txteval echo "$(cat evalExample.txt)"

The string, containing Bash variables, can be assigned to a variable or be present in a file. In our example we have considered both the string and the file. We used the eval command to substitute these variables since eval adds them to the environment of the current shell. Since the current shell now has these variables with values assigned, wherever Bash spots this variable, it will substitute it with the value it holds.

The string str has a particular string with environment variables. Using the eval command, we are able to expand them in the string and print it on the command line. In the latter case, we have redirected that string to a text file named evalExample.txt. While applying the eval command on this file, we get the same outcome.

5. Access Variables within Variables

With eval we can also have an additional layer of evaluation of the variables before executing the final command. We have to assign value to a variable and also assign the name of that variable to another variable. With the help of the eval command, we can have access to the value present in the first variable, from its name which is the value stored in the second variable.

Example:

varA="varB"varB="echo Good day"eval \${$varA}

In this example, $varA gets replaced by varB. The backslash is to escape the dollar sign. This ensures the evaluation of the $ character. Then, that string is sent to Bash for execution. The escaped dollar sign “$” and the braces “{}” tell eval to check out the value held inside the variable. The command ${varB} gets evaluated using the parameter expansion resulting in the final command displaying Good day as the output on the terminal.

6. What happens if eval is not used carefully?

If eval is not used properly, it can lead to some unexpected behavior. The eval command gathers the values from variables to create a string, acting as a command, which is then executed. This comes in handy when the content of a command is built dynamically during the script execution.

Now, let us look at an example where we make a mistake with the eval command.

var1=var2var2="sample*"eval echo \$$var1

In this example, we wanted to print the value present in the variable var2. However, we get an unexpected response. This is because if we have accidentally add the echo in the eval command, it will evaluate echo *. As we can see, instead of just printing the value of $var2 it displayed all the files starting with the keyword "sample" present in the current working directory.

Problems may arise if we use the eval command recklessly. When a script, written to use eval on a string, gets received externally outside the script may pose some serious risks as the string might be embedded with malicious instructions. For this reason, to be safe, we should use the eval command with caution.

7. Example

Having learned how eval works, let's see one use case in this example.

#!/bin/bash sum=0str="echo Sum of consecutive numbers between two numbers $1 and $2 is:" if [ $1 -gt $2 ]then str="echo First number is supposed to be smaller than the second" eval $str exit 1fi for ((i=$1;i<=$2;i++))do eval var$i=$i echo "x$i=$i" sum=$(($sum+var$i))done eval $streval echo $sum

In this example, we are trying to find the sum of numbers between any two integers, taken as command line arguments. If the first input is greater than the second, we display an error and exit out. If it is the other way round, we find the sum of the numbers between them.

Outside the for loop we save the echo also in the variable because so that evaluate will execute the echo. We are storing all the numbers between them in variables var$1 till var$2. The eval command ensures we store the "\$i" as a string rather than a value "$i".

Conclusion

  • The eval command is a powerful command-line utility.

  • It concatenates the arguments and then executes as a Bash command.

  • The eval executes the command in the current shell environment.

  • If used recklessly, it can be dangerous.

eval use case example
variable expansions in strings using eval
eval unexpected behavior
evaluate the values of var1 and var2 as a single command.
variables available to the current shell