0

I would like to set a variable in a script and have it outside the script for the next command.

This is what I have:

#!/bin/bash

myExports="TEST='Value 1';export TEST;";

echo Before eval: $TEST
echo '***'

eval $myExports

echo After eval: $TEST
echo '***'

This is how i'm calling it:

./env1.sh ;echo Next command:$TEST

This is the output:

Before eval:
***
After eval: Value 1
***
Next command:
Jason K
  • 1,406
  • 1
  • 12
  • 15
  • can we not call the next script from with in the first script ? And pass the required variable as command line argument ? If not then: Either you can use an environment variable or write it to a file which the next script can read from – Amir Gohar Sep 19 '18 at 20:19
  • I wanted to get a way from wring to a file or passing in the command. We have this same type of script on a another system. – Jason K Sep 19 '18 at 20:51
  • Perhaps the code in a string variable is just for demo purposes, but if you are planning on doing that in production code, please rethink. See also https://mywiki.wooledge.org/BashFAQ/050 and the many questions here on Stack Overflow which link to that as an answer or explanation for why people are having trouble when they try to do similar things. – tripleee Sep 20 '18 at 05:07

1 Answers1

1

you could source your script like...

 #source ./env1.sh; echo Next command:$TEST
 . ./env1.sh; echo Next command:$TEST

As @Jonathon pointed out in the comments Using the . in place of source is more portable.

In fact, if you use this method you don't even need to export the variable.

Just be careful with your variable names when doing this. Even though this is what you want, you are polluting your environment.

I'm not sure what the purpose of the script is, but I tend to avoid eval if ever possible. This modified script would achieve the same result, but again, I don't know what you are trying to do with this.

#!/bin/bash

#myExports="TEST='Value 1';export TEST;";

echo Before eval: $TEST
echo '***'

TEST='Value 1'; export TEST
#eval $myExports

echo After eval: $TEST
echo '***'
Jason
  • 2,493
  • 2
  • 27
  • 27
  • 1
    Avoid `eval` is sound advice. So too is using dot (`.`) or the C shell workalike but Bash-specific `source` (`source` isn't part of Korn shell, or the POSIX shell, or the original Bourne shell) to read the script. However, if the variable is to be made available to another command — whether that's a shell script or an executable — the `export` is necessary. If the variable only needs to be available to the shell that dotted the script, then there's no need to export it, but the `export` is usually necessary. – Jonathan Leffler Sep 19 '18 at 22:02
  • @jonathan that is a good point. I put the export back in and referenced the . in place of source. I always wondered why people preferred to use that in their scripts. I always felt is was kind of cryptic in complex scripts. – Jason Sep 19 '18 at 22:36