System
Linux hosek 4.15.0-48-generic #51-Ubuntu SMP Wed Apr 3 08:28:49 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
Issue
I need to get output as commands, in a bash script, for storing variables.
Example
sed -n '/# Main configuration./,/# Websites./p' webcheck-$category.cfg | sed '1,1d' | sed '$ d'
This command returns these lines:
email_sender='[email protected]'
email_recipients='[email protected]'
How can I read/run these output/lines as commands in script? Is storing this output to the file and then read it by source
command only way?
I tried | source
at the end of the command, but it reads only from files.
I tried echo
at the beginning, but that had no effect.
Thanks.
As pLumo showed you, you can indeed
source
them. However, I would recommend against this. If you have something like this:Then, a year later when you come back and look at this script, you will have no idea where this
email_sender
variable is coming from. I suggest you instead change the command and use one that returns only the variable's value and not its name. That way, you can easily keep track of where each variable comes from:You can use process substitution:
or
Output:
[email protected] [email protected]
bash read builtin handles things like this nicely.
read
reads lines from stdin into variables.-d ''
turns off whitespace splitting, except for newlines.-r
disables\
escapes.cmdA < <(cmdB)
works similarly to cmdB | cmdA, except in the former cmdA is run in ~this~ shell, instead of a subshell, which is required for read to work as expected.