Michael Platings
Michael Platings

Reputation: 3155

Executing generated commands in bash

I want to run a series of bash commands generated by a Python script. The commands are of the form export foo="bar" and alias foo=bar. They must modify the environment of the current process.

This works great:

$(./generate_commands.py)

until an export command contains a space e.g. export x="a b". This generates an error, and only "a is exported (quotes included).

Currently I'm working around this by outputting generate_commands to a temporary file and sourcing that, but is there a more elegant solution?

Upvotes: 2

Views: 1320

Answers (2)

Alex
Alex

Reputation: 11090

./generate_commands | bash

This will pipe the output of the script as input to bash

Edit:

To allow for variables to be visible in the current shell, you need to source the output:

source <(./generate_commands)

or

. <(./generate_commands)

Upvotes: 5

gongzhitaao
gongzhitaao

Reputation: 6682

I think the OP's problem is

cmd="export x=\"a b\""
${cmd}

does not work, but

export x="a b"

works. My way around this is

export x="a"
echo $x
x+=" b"
echo $x

Upvotes: 0

Related Questions