alfredopacino
alfredopacino

Reputation: 3241

Share a variable among bash scripts

I have 2 bash scripts:

set.sh

export MYVAR="MYVALUE"

get.sh

echo "MYVAR: $MYVAR"

usage

> ./set.sh && ./get.sh

I'm trying to share the variable among the scripts. The real code is more complicated and involves more than 2 scripts, so I cannot call the second script from the first one like that

export MYVAR="MYVALUE"
./get.sh

Upvotes: 0

Views: 122

Answers (2)

Ivan
Ivan

Reputation: 7287

Set them as arguments to the scripts

./set.sh "$MYVAR" && ./get.sh "$MYVAR"

Upvotes: -1

Kolazomai
Kolazomai

Reputation: 1161

I can think of several tries:

  1. Via third script: Use a third environment script and source it in set.sh and get.sh. Probably you can't do that because set.sh has a lot of logic.
  2. Via code: source set.sh in get.sh and add specific logic to set.sh to recognize if set.sh is sourced or executed.
  3. Via pipe: Have you thought about using a pipe for interprocess communication between set.sh and get.sh? You could send MYVAR from set.sh to get.sh through the pipe, and only start executing in get.sh once this information has arrived.
  4. Via file: Use a file to transmit the value of MYVAR by writing it from set.sh to the file and reading from the file in get.sh.
  5. Via output: Write MYVAR to the output in set.sh and consume (or parse) the output of set.sh in get.sh.

Upvotes: 2

Related Questions