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 create a string result from my shell script and i want to execute it as a shell command.

For example file_a is:

user1@gmail.com
user2@gmail.com

script:

awk '{print "mail -s \"welcome\"", $1}' file_a

And result:

mail -s "welcome" user1@gmail.com
mail -s "welcome" user2@gmail.com

So i want to execute the result as a set of shell commands.

share|improve this question
add comment

5 Answers

up vote 3 down vote accepted

You want to look into the eval command.

eval $(awk '{print "mail -s \"welcome\"", $1}' file_a)

EDIT: You're right @manatwork--eval as I demonstrated wouldn't really work for multiple lines. I was trying to answer Navid's question as he asked it, but really I shouldn't have been afraid to ask him why he wasn't just using a for loop, i.e.:

for m in $(<file_a); do mail -s welcome $m
share|improve this answer
    
Are you sure? For me this works only for single line output, not with multiple lines as in the requirement. –  manatwork Feb 28 '12 at 11:18
add comment

A couple of ways:

  • write the output of awk to a file, make the file executable, and then execute it
  • use the system() function in the awk script:
share|improve this answer
add comment

Directly reading and executing command in bash.

for i in `<file_a`; do mail -s "welcome" $i; done
share|improve this answer
add comment

You can play with xargs.

xargs - build and execute command lines from standard input

And a example couple be like this

awk '{print "mail -s \"welcome\"", $1}' file_a | xargs -0 bash -c
share|improve this answer
add comment

You could pipe the result of àwk to bash:

awk '{print "mail -s \"welcome\"", $1}' file_a | bash

But be careful on the output of the 1st command, as if file_a contains some tricky lines, you could execute unwanted commands.

share|improve this answer
add comment

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.