1

I have a shell script that declares some variables:

export X=1
export Y=2

and I'd like to be able to do something like this:

. ./path/to/script | command_that_has_access_to_X_and_Y

Basically, source the script somehow, so that the command following the pipe could access those variables. Is such a thing possible?

One of the commands I'd like to run is pg_dump, and the credentials are in a shell file:

Basically I'm trying to run this:

bash -c "pg_dump \$PRODUCTION_DB --password \$PRODUCTION_PASSWORD --user \$PRODUCTION_USERNAME --host \$PRODUCTION_HOST > #{backup_name}.sql"
4
  • what about passing it as variables? like script | command "$X" "$Y". If you want to push the changes upstream then you will have to use a file. Commented Sep 8, 2013 at 14:18
  • Using them as variables would be just what I need. One of the commands I'm running is pg_dump, and I'm passing it the credentials to the DB.
    – Geo
    Commented Sep 8, 2013 at 14:21
  • Why don't you just return them? X=$(command "$X"). Doing that for two variables might require some parsing but it's not that hard Commented Sep 8, 2013 at 14:28
  • Could you elaborate a bit on the parsing part? I'm not sure I understand completely what you mean.
    – Geo
    Commented Sep 8, 2013 at 14:31

2 Answers 2

2

There's no need to use a pipe. Assuming you have the export commands in the first script, those variables will be available to the second script.

. ./path/to/script
command_that_has_access_to_X_and_Y

A pipeline is simply a tool for connecting the standard input of one script to the standard output of another. It's an efficient alternative to using a temporary file; x | y is more-or-less the same as

x > tmp.txt
y < tmp.txt

except the operating systems handles the details of passing text from x to y so that both can run at the same time, with y receiving input as x produces it.

1
  • You're so right. I have no clue why I've complicated myself such :D. Thank you!
    – Geo
    Commented Sep 8, 2013 at 16:08
1

You could send by echo instead:

Script on the left:

#!/bin/bash
X='Something X'
Y='Something Y'
echo "$X"
echo "$Y"

Command on the right:

... | bash -c "read -r X; read -r Y; echo \"\$X : \$Y\""

Produces:

Something X : Something Y

Not the answer you're looking for? Browse other questions tagged or ask your own question.