Export variables between shell script

I have two independently executable scripts. we can say first that script A computes some values. And I want to repeat these values โ€‹โ€‹from other scripts called B. These scripts will not call each other. I used the export keyword but did not work. How can i do this?

+6
source share
6 answers

If I understood this requirement, then both scenarios cannot simply be executed in the same subcommand independently of each other, but without , calling each other, or without the need to use an external file or channel as follows:

Let's say this is your script1.sh

#!/bin/bash # script1.sh: do something and finally export x=19 

And here is your script2.sh

 #!/bin/bash # script2.sh: read value of $x here echo "x="${x} 

Just name them in the same sub-shell like this

 (. ./script1.sh && ./script2.sh) 

CONCLUSION:

 x=19 
+6
source
  mkfifo /tmp/channel process_a.sh > /tmp/channel& process_b.sh < /tmp/channel& wait 

Of course, you can also just read a single line whenever you want.

There are coprocs in bash, which may also be what you want. Random example from this page.

 # let the output of the coprocess go to stdout { coproc mycoproc { awk '{print "foo" $0;fflush()}' ;} >&3 ;} 3>&1 echo bar >&${mycoproc[1]} foobar 

ksh has a similar function obviously

+4
source

Think of each script as a function: function A evaluates some value and returns it. He does not know who will call it. Function B takes on some value and echoes it. It doesnโ€™t matter who produced this value. So script A:

 #!/bin/sh # a.sh: Calculate something and return the result echo 19 

and script B:

 #!/bin/sh # b.sh: Consume the calculated result, which passed in as $1 echo The result is $1 

Make them doable:

 chmod +x [ab].sh 

Now we can glue them together on the command line:

 $ b.sh $(a.sh) The result is 19 

Semantically, b.sh did not call a.sh. You called a.sh and passed its result to b.sh.

+1
source

Can you read the third file, say settings.sh, with the common exported variables?

 # common.sh export MY_PATH=/home/foo/bar/ export VERSION=42.2a 

and in both A and B source common.sh to load these values.

Please note that export may not be required in this case.

0
source

You can display values โ€‹โ€‹in files, and another script can read them. If you want to use it as a parameter for something, use the reverse apostrophe:

 echo `cat storedvalue` 

Be careful if both scenarios work at the same time, concurrency problems can occur that can cause rare, mystical looking errors.

0
source

In fact, all you need is source , you can skip the export prefix.

My use case was an environment-specific settings file, for example:

Inside main_script.sh

 THIS_DIR=`dirname $0` source $THIS_DIR/config_vars.sh # other commands 

Inside config_vars.sh

 LOCAL_ROOT="$HOME/folder/folder" REMOTE_USERNAME='someuser' BACKUP_FOLDER="$LOCAL_ROOT/folder" # etc. 
0
source

Source: https://habr.com/ru/post/885990/


All Articles