I create a string result from my shell script and i want to execute it as a shell command.

For example file_a is:



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.


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

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:

Directly reading and executing command in bash.

for i in `<file_a`; do mail -s "welcome" $i; done

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

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.

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.