Explaining ‘eval’ in Bash
The aim of this page📝 is to explain the usage and functionality of the eval command in Bash scripting, based on the particular example of the expression `eval “$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)”` from Homebrew for Linux installer
- For terminology, see Eval Apply
- evaluate means get the meaning/value of the given symbol
- apply means execute an operation, do, things with the values, execute
evalis a bash internal command so it is described in the bash man page.
eval [arg ...]
The args are read and concatenated together into a single com-
mand. This command is then read and executed by the shell, and
its exit status is returned as the value of eval.
If there are no args, or only null arguments, eval returns 0.
- Usually, it is used in combination with a Command Substitution.
$(...)syntax is used for command substitution in Bash.
- Without an explicit
eval, the shell tries to execute the result of a command substitution, not to evaluate it.
- Say that you want to code an equivalent of
- Note the difference in how the shell handles the writings of
$( echo VAR=value )
bash: VAR=value: command not found
- The shell tries to execute
VAR=valueas two separate commands.
- It throws an error about the second string. The assignment remains ineffective.
eval $( echo VAR=value )
eval, shell merges (concatenates) the two strings
VAR=value→ parses this single unit according to appropriate rules → executes (applies) it as a shell command
- Command substitution runs the command inside the parentheses.
- The output of the command is then substituted in place.
- Last but not least, eval can be a very dangerous command.
- Any input to an eval command must be carefully checked to avoid security problems.
Example from Homebrew for Linux Installer
eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"`.
This line of code is typically added to a shell startup file. When a new shell session is started, this line is executed. It runs the
brew shellenv command, captures its output, and then executes the output as shell commands using
eval. This sets up the necessary environment variables for Homebrew.
- In the given expression, the command inside the parentheses is
brew shellenvis a command provided by Homebrew.
- Homebrew is a package manager for macOS, but it also works on Linux.
brew shellenvcommand outputs shell commands.
- These commands are needed to configure the environment for Homebrew.
- The output typically includes
exportstatements set various environment variables needed by Homebrew.
evalcommand then executes these
- This configures the current shell environment for use with Homebrew.
- This is often done in shell startup files like
- It ensures that the necessary environment variables for Homebrew are set for every new shell session.