You can achieve the desired result without a loop and without eval
.
source <(echo "$output")
The <()
construct is a process substitution. It executes the command found inside, creates a FIFO (special first-in, first-out file), and is then transformed into an actual file path (pointing to the FIFO) which source
can read from.
Of course, you could also store the actual assignments in a file rather than putting them in the output
variable.
source config_file
The source
command (or its more standard form .
) reads commands from a file and executes them in the current shell, without launching a separate process or subshell, so variable assignments in sourced files work. Useful for config files, but of course you must be sure no one can put arbitrary commands in those files as that would be a security risk.
IMPORTANT
If you want to put declarations in a script (set_token.sh
in your case), this script must be sourced (i.e. executed with source
or .
), not executed with bash
or by calling it directly (if it is executable). Any method other than source
or .
will launch a child process, and there is no way for a child process to assign variables that will be visible to the parent process afterwards. Sourcing does not create a separate process, which is why assignments will work. The export
keyword will make assignments visible to children process only, they cannot make assignments visible to the parent.