Shell – What are some useful use-cases for eval in Shell

evalshell

You hear it a lot eval is evil, whether it's in Shell/POSIX world, or in other langs like python etc…

But I'm wondering, is it actually useless? or is it there some arcane, non-documented, interesting or just useful use-cases for it?

Would prefer if the answer is sh/bash centric, but it's fine if it's about other Shells too.

PS: I'm well aware why eval is considered evil.

Best Answer

I know of two ... common ... use cases for eval:

  1. Argument processing with getopt:

    [T]his implementation can generate quoted output which must once again be interpreted by the shell (usually by using the eval command).

  2. Setting up an SSH agent:

    [T]he agent prints the needed shell commands (either sh(1) or csh(1) syntax can be generated) which can be evaluated in the calling shell, eg eval `ssh-agent -s` for Bourne-type shells such as sh(1) or ksh(1) and eval `ssh-agent -c` for csh(1) and derivatives.

Both uses might have alternatives, but I wouldn't bat an eyelid on seeing either of them.