Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Consider you have a file with some sort of terminal command. How might each line be executed? Can you pipe the output of more into an eval?

%> more ./foo.txt

Edit:

After some help/guidance from the comments, I think I should also make note that it's been a while since I've done any shell scripting, so while I say eval I may mean echo or some other way of executing code.

If foo.txt contains various lines of code, but I want to execute the line that contains echo 'bar bar', I'm looking for a way to do that from, let's say a grep. Something logically similar to:

grep echo foo.txt | xargs echo
share|improve this question

1 Answer 1

up vote 3 down vote accepted

If you just need to evaluate every line of a file, you don't need a complicated eval or stdout redirection. Two easy options:

  • Source the file (source filename.sh or . filename.sh).
  • Make the file executable and run it (chmod +x filename.sh; ./filename.sh)

If you really need to eval each line of a file in a loop, do it with while:

while IFS= read -r line; do eval "$line"; done < filename.sh

You can also pipe the output of any command to while:

grep foo filename.sh | while IFS= read -r line; do eval "$line"; done

If you need to pass something to source (or .), which expects a file name as an argument, you can use process substitution:

source <( grep foo filename.sh )
share|improve this answer
    
I like, but is there a way to do this w/o using bash? I know I tagged it, so I'm just curious, since I don't always use it. –  vol7ron Apr 15 '13 at 14:38
    
source isn't Bash-specific and should work in most other shells (Bourne Shell, (t)csh) as well. –  slhck Apr 15 '13 at 14:48
    
Right now, source would work but I like to think ahead in the case that there are lines I wan't to strip out and possibly use the output of grep –  vol7ron Apr 15 '13 at 14:59
2  
Technically, source is a non-standard synonym for .. –  chepner Apr 15 '13 at 15:08
    
@chepner: right, but can you pump more/grep into an eval (guessing echo) from the terminal command line? Perhaps into find -exec? –  vol7ron Apr 15 '13 at 17:27

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.