Source a Here Document in Bash – How to Guide

bashhere-documentshell

Let's say I have a bash script that acts as a config file for another bash script:

config.sh:

verbose=yes
echo "Malicious code!"
name=test

script.sh:

source config.sh
echo "After sourcing: verbose='$verbose', name='$name'"

The problem is, this isn't very secure, as anything put in config.sh gets run:

$ ./script.sh
Malicious code!
After sourcing: verbose='yes', name='test'

To make it more secure, I thought I'd grep out assignment operations and only execute those. I would accomplish by passing source a "here document":

script.sh:

source <<EOF
$(grep -P '^\s*\w+=' test.sh)
EOF
echo "After sourcing: verbose='$verbose', name='$name'"

(Yes, I know the regex isn't that strong; it's just a placeholder.) Sadly, source doesn't seem to play well with here docs:

./script.sh: line 1: source: filename argument required
source: usage: source filename [arguments]
After sourcing: verbose='', name=''

Obviously I could do any number of things to get config data from a file, and that's likely more secure anyways.

But I'm still left with this itch; I want to figure out if what I've tried can work. Any suggestions?

Best Answer

source needs a filename, you can't redirect input to it.

On my system, I was able to use Process substitution instead:

source <( grep = test.sh )

Replace = with the appropriate regular expression.

Related Question