Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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"
share|improve this question
1  
Isn't automatic execution in this fashion a teensy bit dangerous? –  Faheem Mitha Jun 30 '11 at 13:35
1  
@Faheem and @avilella: More than a teensy bit, rather dangerous indeed! Also, somewhat fragile. –  Caleb Jun 30 '11 at 19:21

3 Answers 3

up vote 1 down vote accepted

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)"
share|improve this answer
    
Note that you need double quotes around variable substitutions, or else whitespace will get mangled and wildcards expanded at the wrong time, then again at the right time. –  Gilles Jun 30 '11 at 20:48

To evaluate the lines in a separate shell process:

grep somedir INSTALLFILE | sh

To evaluate the lines in the running shell process:

eval "$(grep somedir INSTALLFILE)"
share|improve this answer
    
+1 for being the the only one to see the forest through the trees. Hereby deleting my answer. @avilella: for convenience you can use -A 1 or -B 1 as flags on one or the other of your greps to fetch both lines with one grep and use that in either of @Gilles solutions. –  Caleb Jun 30 '11 at 21:20

Have you considered using the 'exec' feature of find as in:

find somedir -name INSTALLFILE -exec {}\;
share|improve this answer
    
I think the OP is looking to execute the results that come back grom grep, not the run every result that comes back from find. –  Caleb Jun 30 '11 at 13:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.