The eval command is a built-in utility that interprets and executes arguments as shell commands. These commands are stored inside a string. In this article, I have explored how to use the eval command in bash, incorporating some practical examples to ease your learning.
What is “eval” Command in Bash?
The eval command in Bash is a utility that executes arguments as the shell command. Here, it combines the arguments into a single string and uses it as input to the eval command. Then it executes the commands inside the string.
The basic syntax of the eval command is:
eval [arguments]
Here, [arguments]
are strings that contain commands to be executed.
8 Practical Examples Using “eval” Command in Bash
In this section, I have listed some practical examples of implementing eval command in Bash on storing a command in a variable, command substitution, converting input, executing a command inside the loop, analyzing field value, accessing a variable within another variable, variable expansion, and setting current shell variable.
1. Store Command in a Variable
Storing a command with a proper option or flag in a variable eases running that command in the shortest possible time whenever necessary. Here, I will store a command to know the total word count inside a file by following the syntax: variable_name = “wc -w file_name”
. Below is a complete bash script:
#!/bin/bash
variable="wc -w file2.txt"
eval "$variable"
At first, the variable is defined and it contains the wc -w file2.txt
string. After that, the eval command executes the wc -w file2.txt
command and saves it inside the variable as a string. It finds the total word count of the text inside the file2.txt.
The image shows that the wc -w
command found the total word count inside the file2.txt.
2. Command Substitution with “eval” in Bash
Command substitution replaces the output of a command contained inside the string with its output. The syntax is, variable="echo $(command)"
. This stores the command, along with an echo command, as a string in the variable. To execute the command within the variable, you can use the eval command. Below is a Bash script demonstrating how to obtain the current date and time using command substitution and the eval command:
#!/bin/bash
variable="echo \$(date)"
eval "$variable"
At first, the variable is defined, and the echo \$(date)
string is assigned as a value. Then eval command executes the command stored inside the variable as a string. Here within the string \$(date)
represents command substitution, which will be replaced by the current date.
The eval command has printed the current date and time on the terminal.
3. Convert Input Using “eval” with “tr” Command
Converting the case of the input means keeping the input in a specific case format. The tr command with the eval command helps to convert the case of a string properly. For this purpose, follow the syntax: eval "string_variable=\$(tr '[:upper:]' '[:lower:]' <<< "$string_variable")"
. Here is a bash script to convert all the letters to lowercase:
#!/bin/bash
# Ask the user to enter the string
read -p "Enter variable 1: " variable1
# Convert values to lowercase using eval
eval "variable1=\$(tr '[:upper:]' '[:lower:]' <<< "$variable1")"
# Print the lowercase values
echo "Variable 1 (lowercase): $variable1"
The read -p "Enter variable 1: " variable1
command takes input from the user and stores it in variable1. After that, the eval command translates the uppercase letters to lowercase utilizing the tr command.
The image shows that the tr command with the eval command has converted all the letters to lowercase.
4. Usage of “eval” Command within Loop
The eval command is dynamic and can execute the command inside a loop on each iteration. Here, I will execute a command utilizing the eval command from inside a loop on each iteration. Follow the complete bash script to know the details:
#!/bin/bash
for i in {1..5}; do
eval "echo 'Count: $i'"
done
Here, for i in {1..5};
command iterates over from 1 to 5. Then, the eval command executes the command inside the echo 'Count: $i'
string and prints every iteration variable on the terminal. Here, $i
represents the current value of i on each iteration.
Upon execution, the eval command has executed a command inside the loop on each iteration.
5. Analyzing Field Value with “eval” in Bash
Analyzing field value means processing data and coming to a conclusion. The eval command offers users some features to analyze field values dynamically. Here, I will develop a bash script that will prompt a user to enter a value and then check whether the number is even or odd. Follow the script below to do this:
#!/bin/bash
# Prompt the user to enter field values
read -p "Enter a number: " value
remainder=$(( value % 2 ))
# Analyze the field value using if statements
if [ "$remainder" = "0" ]; then
eval "echo "$value is Even""
else
eval "echo "$value is Odd""
fi
The read -p "Enter a number: "
value command prompts the user to enter a value, and the remainder=$(( value % 2 ))
command calculates the remainder after dividing the value by 2. Then, "$reminder" = "0"
inside the if statement checks if the remainder’s value is 0. According to the result, it prints a message on the terminal.
The command has checked and found that 5 is odd.
6. Access Variable Within Variable
Accessing a variable within another variable means accessing the value stored inside the first variable by mentioning the second variable name. Here, I will print the content of the file1.txt file:
#!/bin/bash
title="file1.txt"
name=title
command="cat"
eval $command \${$name}
The title="file1.txt"
command defines a variable named title and stores the file1.txt file to the variable. After that, the name=title
command assigns the “title” string to the variable ‘name’ and the command="cat"
command assigns the “cat” string to the variable ‘command’. Then, the eval command executes the $command \${$name}
command. Here $command
expands to the value of the variable ‘command’, which is “cat” and \${$name} is a bit convoluted. First $name
expands to the value ‘title’. Then ${title}
expands to the value “file1.txt”. Eventually, the whole eval command executes the cat file1.txt command.
7. Variable Expansion in String
Variable expansion means replacing the variable with its value. It enables users to use the value of a variable wherever necessary. I have a file named file3.txt. The string inside the file3.txt is:
Hello $USER! It is $(date). Welcome to $HOSTNAME.
Now execute the below command to avail the value of the current user, the current hostname with the current date and time.
eval echo \"$(cat file3.txt)\"
At first, \"$(cat file3.txt)\"
captures the content of the file3.txt file. If there is any variable or command substitution within file3.txt, it will be expanded. After that, in the echo \"$(cat file3.txt)\"
construct, there are double quotes around the $(cat file3.txt)
command, ensuring the output is treated as a single argument to the echo command.
Finally, the eval command evaluates and executes the constructed echo command where $USER
and $HOSTNAME
are expanded to the current user name and hostname, respectively. And $(date)
is a command substitution that will be replaced by the current date and time. The eval command forces the expansion of variable and command substitution within the content of file3.txt.
The image shows that the current username and hostname have replaced the $USER and $HOSTNAME.
8. Setting Variables in Current Shell
The current shell variable exists only on the current shell and gets deleted when the shell is closed. For data manipulation and mathematical calculation, setting variables in the current shell is vital. In this example, I have a text file that contains the declaration command of var1
and var2
variables. Content of set_var.txt is:
echo "Setting variables in Current Shell"
var1=Linux
var2=Simply
Now execute the below command to execute the command inside the set_var.txt file.
eval "$(cat set_var.txt)"
The cat set_var.txt
command reads the content of the set_var.txt file. Then, the eval command treats the content as a series of shell commands and executes them in the current shell environment. Hence, the var1=Linux
and var2=Simply
commands declare two variables and assign values to them.
Now execute the command to access the current shell variable:
echo $var1 $var2
The var1 and var2 are two current shell variables.
Exploring Alternatives to Bash Eval
There are also some different approaches to executing commands stored as strings. In this section, I have discussed the command substitution and the process substitution:
1. Command Substitution
Command substitution captures the output of a command and stores it in a variable. The syntax for command substitution is variable=$(command)
. Here, I will find the list of contents in the current directory. The complete bash script is below:
#!/bin/bash
list=$(ls -l)
echo "$list \n"
First, list=$(ls -l)
command executes the ls -l command that lists the contents of the current directory with permission details and keeps the output to the list variable. Then, the echo "$list \n"
command prints the contents of the variable ‘list.’
All files inside the current distribution have been listed on the terminal utilizing the command substitution.
2. Process Substitution
The process substitution feature in Bash allows the output of a command to be treated as a temporary file. The syntax for process substitution is <( )
. In this example, I will compare the contents of two directories, directory1
, and directory2
, utilizing the process substitution and the diff command. For this, execute the below command:
diff <(ls directory1) <(ls directory2)
Here, the diff <(ls directory1) <(ls directory2)
command implements process substitution. The (ls directory1)
and (ls directory2)
command find the list of files and directories inside the directory1
and directory2
and create two temporary files. After that, the redirection operator is used to pass these files as input to the diff command. Finally, the diff command compares the files line by line, which means comparing the contents of the two directories and printing out the differences.
The diff command shows the difference between the content inside directory1 and directory2 by utilizing process substitution.
Here’s a quick comparison of these methods is given below:
Method | Bash Eval | Command Substitution | Process Substitution |
---|---|---|---|
Pros | Executes the commands stored inside a variable as a string. | Captures the output of a command and stores in another variable. | Passes the output of a command as an input file to another command. |
Cons | There are high-risk or command injection vulnerabilities. | It is not an appropriate approach for executing commands stored in string. | It is not an actual substitution process rather it is a file-passing process. |
Warning: Command injection vulnerabilities are one of the most common issues that happen when the eval command executes a command according to user input. This allows system attackers to access vital information and manipulate it.
Here is an example of a bash script where potential command injection vulnerability prevails:
#!/bin/bash
read -p “Enter a path: ” p
eval ls $p
This script allows an unauthorized user to list all contents inside the current directory and remove them from the system forcefully if the user inputs rm -rf *
. To prevent this type of vulnerability, do not execute any command incorporating user input.
Conclusion
This article has explored different aspects of using the eval command in Bash. It will equip the young learner to implement the eval command in their bash script to accomplish their task. If you have any thoughts, do not hesitate to comment below.
People Also Ask
What is the Bash Eval Command and How Do I Use It?
The Bash eval command is a utility that executes commands stored inside a string. At first, write a command inside a string following the syntax: variable_name="commands"
. After that, execute the command stored inside the variable_name utilizing the eval command. For this, follow the syntax: eval $variable_name
What is the difference between exec and eval Bash?
The difference between exec and eval commands is that the eval command evaluates the result of the string assigned to it. On the other hand, the exec command replaces the current shell process with a specific new command.
Is exec safer than eval?
Yes, exec is safer than eval. The eval command can execute any command given to it as input, which might be problematic in case the user provides harmful command input. On the other hand, the exec command is free from this potential.
What type of command is eval?
The eval command is a built-in Linux command that executes arguments as a shell command. The command executes the command stored inside it after evaluating the argument.
Related Articles
- How to Convert a Bash String to Int? [8 Methods]
- How to Format a String in Bash? [Methods, Examples]
- How to Convert Bash String to Uppercase? [7 Methods]
- How to Convert Bash String to Lowercase? [7 Methods]
- How to Replace String in Bash? [5 Methods]
- How to Trim String in Bash? [6 Methods]
- How to Truncate String in Bash? [5 Methods]
- How to Remove Character from String in Bash? [7+ Methods]
- How to Remove First Character From Bash String? [7 Methods]
- How to Remove Last Character from Bash String [6 Methods]
- How to Use String Functions in Bash? [Examples Included]
- How to Generate a Random String in Bash? [8 Methods]
- How to Manipulate Bash String Array [5 Ways]
- How to Use “Here String” in Bash? [Basic to Advance]
- Encode and Decode with “base64” in Bash [6 Examples]
- How to Get the First Character from Bash String? [8 Methods]
<< Go Back to String Manipulation in Bash | Bash String | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners