Using `eval` Directly on the Results of Command Substitution Considered Harmful

I use the following pattern quite a lot in my Bash scripts:

#!bin/bash

set -e
eval $(command_with_shell_output)
# act on new environment variable

Here, the output of a command gives us some shell statements (like possibly exporting some environment variables) which the shell evaluates in the context of the script. ssh-agent is an example of a command that follows this pattern, for example.

set -e tells Bash to stop running the script of any commands fail. This is good. But the problem is, when command_with_shell_output fails, the script keeps running! The way around this is to break out the command substitution and evaluation into separate statements:

#!bin/bash

set -e
output=$(command_with_shell_output)
eval "${output}"
# act on new environment variable

This will successfully stop the script from carrying on if the command substitution fails.