Using source to include part of a file in a bash s

2019-08-11 22:03发布

问题:

I've a bash script that need to use some variables included in a separate file.

Normally, for including the entire file I would use source otherfile.sh in the main script. In this case I need to use just a portion of this file. I can't use (include) the rest of the variables included in the rest of the file.

To filter the content of the config file (let's say just as example from the tag "# start" to "# end") I use awk, but I can't redirect the output to the soruce command.

Below my code:

awk ' /'"# start"'/ {flag=1;next} /'"# end"'/{flag=0} flag { print }' config.sh

Do you know any way to redirect the output of this command into source? Is there any other way to include the output in my bash script at run-time?

By the way, I wouldn't like to create temporaty files (it seems me too dirty...)..and I've tried something found on this site, but for some reasons it doesn't work. Below there's the solution I've found.

awk ' /'"# start"'/ {flag=1;next} /'"# end"'/{flag=0} flag { print }' config.sh | source /dev/stdin

Thank you,

Luca

回答1:

source can read from a process substitution in bash:

source <( awk ' ... ' config.sh )

sed allows a simpler way to get the subset of lines:

sed -n '/#start/,/#end/p' config.sh

UPDATE: It appears that this may only work in bash 4 or later.



回答2:

A correct way of doing it provided by a friend today. Here's the code:

source /dev/stdin <<EOF
$(awk ' /'"# 10.216.33.133 - start"'/ {flag=1;next} /'"# 10.216.33.133 - end"'/{flag=0} flag { print }' testbed.sh)
EOF

Working perfectly...thanks Andrea! :) (and of course everyone tried to answer)