3

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Chepner, I tried to execute the code above but using 'source <(sed -n '/#start/,/#end/p' config.sh)' returns line 7: source/dev/fd/63: No such file or directory. Using 'source<$(sed -n '/#start/,/#end/p' config.sh)' says line 7: $(sed -n '/#start/,/#end/p' config.sh): ambiguous redirect. I report the correct answer given by a friend today below. Thank you anyway!
Strange. I tried source <(echo foo=bar), which should set the value of foo to "bar" in the current shell. It works as expected in bash 4.1 and above. It does fail in bash 3.2, although I don't see any error message as you report with the first attempt. The second attempt should fail, since you are trying to use the output of sed as a file name, which is syntactically incorrect, I think.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.