Bash – how to execute lines coming from a grep result

bashgrep

I've got a text file with certain installation instructions, and I know I can grep for a unique occurrence in the file. For example, the text file has something like:

MYDIR=`find /home/user -name somedir`
export PERL5LIB=$PERL5LIB:$MYDIR

In bash, how can I execute the lines after a grep in the file?
Something like:

execute result from "grep somedir INSTALLFILE"
execute result from "grep 'export PERL5LIB' INSTALLFILE"

Best Answer

Assumptions:

  • you have control over this file and are not in danger of malicious code
  • you want to set these variables your current shell

You could redirect your commands to a temp file and execute that:

tmp=$(mktemp)
{
    grep somedir INSTALLFILE
    grep 'export PERL5LIB' INSTALLFILE
} > "$tmp"
. "$tmp"

Or you could evaluate the results

eval "$(grep somedir INSTALLFILE)"
eval "$(grep 'export PERL5LIB' INSTALLFILE)"

Updating an old answer. What I would do today is use a process substitution:

source <(
    grep somedir INSTALLFILE
    grep 'export PERL5LIB' INSTALLFILE
)
Related Question