13

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

3 Answers 3

14

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)"
2
  • +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
    Commented Jun 30, 2011 at 21:20
  • Note that on some systems sh may be a symlink to another shell instead of the one you were expecting, so results could be unpredictable. To be safe, specific the exact shell you're expecting, e.g. grep somedir INSTALLFILE | bash
    – thdoan
    Commented Apr 10, 2017 at 2:54
4

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
)
1
  • Note that for source <(...), you need bash 4 or above. It didn't work with older versions (zsh was OK though). Commented Feb 5, 2016 at 16:29
-2

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

find somedir -name INSTALLFILE -exec {}\;
1
  • 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
    Commented Jun 30, 2011 at 13:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .