Bash: The `eval` Command
The eval command executes its arguments as a single Bash command. It is most often used to execute dynamically created commands or to deserialize data that was previously serialized into a string.
General Syntax and Basic Usage
#!/bin/bash
# Dynamically create a command as a string
my_command_string="ls -l"
# The `eval` command executes the content of the string
eval "$my_command_string"
The eval command takes the string "$my_command_string" and executes it as if it were typed directly into the terminal.
Warning: eval is a very powerful tool, but it can be dangerous if it executes a string from an untrusted source (e.g., from a user), as it could execute malicious code.
Handling Non-Executable Strings
If the string passed to eval is not a valid command, Bash will report an error, just as it would if you typed the command directly into the terminal. The output of the command (or the error) is written to the standard output (stdout) or standard error (stderr), just like any other command.
#!/bin/bash
my_string="this is not a command"
eval "$my_string"
# Output in console:
# bash: this: command not found
In this example, eval attempts to execute "this is not a command", which results in a "command not found" error because "this" is not a recognized command. The output is written to standard error.
Serializing and Deserializing a Single Array
eval combined with declare -p is a common and reliable pattern for storing and restoring complex variables like arrays.
#!/bin/bash
# 1. Create and populate an array
declare -a my_array=("apple" "banana" "cherry")
# 2. Serialize the array into a string
# The string will look like: `declare -a my_array='([0]="apple" [1]="banana" [2]="cherry")'`
array_string="$(declare -p my_array)"
# 3. Clear the array from memory
unset my_array
# 4. Deserialize the array from the string
eval "$array_string"
# 5. Verify that the array has been restored
echo "First element: ${my_array[0]}" # Result: First element: apple
The eval "$array_string" command re-executes the serialized code, which re-creates the my_array variable in the current shell. The result of the command execution (in this case, the re-creation of the variable) is stored in the variable itself.