Olivier Pons
Olivier Pons

Reputation: 15788

How to execute command line via input

I've read this and this, but didn't make it work.

Here's my script:

env -i MY_KEY=$my_key MY_ACCOUNT=$my_account command-that-outputs-a-list \
    | grep "name" | awk -v src=$src \
    '{a = substr($2,2, length($2)-3); print "my_copy_cmd -s xx-yy/"src"/"a" -d . "}'

and it output things like:

my_copy_cmd -s xx-yy/source-file-name -d .
my_copy_cmd -s xx-yy/source-file-name -d .
my_copy_cmd -s xx-yy/source-file-name -d .
my_copy_cmd -s xx-yy/source-file-name -d .

Now I'd juste like to execute it in the same line, but xargs makes all incoming into one line of arguments (and it doesn't run it). xargs -0 doesn't work either. And I'd like to run it using env -i to run it in an environment without variables, and to set temporarily my env variables (= like I did at the very first command), something like (which doesn't work):

env -i MY_KEY=$my_key MY_ACCOUNT=$my_account command-that-outputs-a-list \
    | grep "name" | awk -v src=$src \
    '{a = substr($2,2, length($2)-3); print "my_copy_cmd -s xx-yy/"src"/"a" -d . "}' \
    | xargs env -i MY_KEY=$my_key MY_ACCOUNT=$my_account 

Upvotes: 0

Views: 456

Answers (2)

Ron
Ron

Reputation: 6601

Does this work:

env -i MY_KEY=$my_key MY_ACCOUNT=$my_account command-that-outputs-a-list \
    | grep "name" | awk -v src=$src \
    '{a = substr($2,2, length($2)-3); print "my_copy_cmd -s xx-yy/"src"/"a" -d . "}'|while read z;do $z 2>&1 ;done

The while loop will read each whole line from the output, and just execute it.

Upvotes: 1

Thomas
Thomas

Reputation: 181825

Try piping the output into sh or bash. You can set variables by adding the assignment before the command:

$ echo 'echo variable is $my_var' | my_var=foo bash
variable is foo

So something like this should work:

env -i MY_KEY=$my_key MY_ACCOUNT=$my_account command-that-outputs-a-list \
    | grep "name" | awk -v src=$src \
    '{a = substr($2,2, length($2)-3); print "my_copy_cmd -s xx-yy/"src"/"a" -d . "}' \
    | MY_KEY=$my_key MY_ACCOUNT=$my_account bash

I find that this is a pretty good trick to assemble and preview a batch of commands before actually executing them.

Upvotes: 0

Related Questions