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`

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

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)"
  • +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
  • 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
    Apr 10 '17 at 2:54


  • 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:

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

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

find somedir -name INSTALLFILE -exec {}\;
  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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