Session and utilities

The eval command

Reads a piece of text again and runs it as if you had typed it in the terminal.

Syntax

eval <texto>Try it in the terminal →

Copy-ready examples

$ cmd="echo hola mundo" && eval "$cmd"stores a command in a variable and runs it with eval.

Example output

hola mundo
$ var=HOME && eval echo \$$varreads the value of a variable whose name is stored in another one.
$ x=5 && eval "echo \$((x * 2))"lets the arithmetic be evaluated in the second pass.

Example output

10

You can try them in the browser terminal: it does not touch your computer.

Common errors

MessageCauseFix
bash: comando_inexistente: command not foundThe text names a command that does not exist. eval runs it just as if you had typed it.Print the text with echo before evaluating it and check the name with type.
bash: X: readonly variableThe text tries to assign a value to a read-only variable.Use another variable name, or check what text reaches eval.

Typical mistakes

  • eval reads the text one more time: if you want a $ expanded later, escape it, as in eval echo \$$var.
  • Quote the variable: eval "$cmd" passes the text as one argument, and the shell does not split it beforehand.
  • If the text has unclosed quotes, eval gives a syntax error and runs nothing.

Differences from similar commands

  • bash -c: also runs a text as a command, but in a new shell: the variables it changes do not reach your session.
  • source: runs the contents of a file in your shell. eval runs a text you write or build on the spot.

Security

Never pass eval text that comes from outside: files, networks, forms or other people's arguments. Whatever it contains runs with your permissions, and eval reads it again, so expansions happen twice.

Related commands

FAQ

Do I need eval to run a command stored in a variable?

For a simple command $cmd is enough. eval is needed when the text contains pipes, redirections or quotes that must be interpreted.

What does eval return when there is nothing to run?

That of the command it ran. With no arguments, or only empty ones, it returns 0.

When is it safe to use it?

When you write the text yourself or build it from values you control. With outside data, do not use it.

Learn to actually use it

The basic Linux course takes you from zero to console fluency with 24 self-grading lessons.

Start the free course