In bash, if I define a variable inside a script (say, set_var.sh
), I can choose whether those definitions persist after "running" the script.
This will depend on how I "run" the script, the options being:
sh set_var.sh
(variables do not persist)./set_var.sh
(variables do not persist, same as point 1)source set_var.sh
(variables persist)
This is irrespective from the variable being exported to the environment or not in set_var.sh
.
Can the same as items 1 and 3 above be achieved with PowerShell 5.1 scripts, for both PS and $env
variables?
For an illustration see (1) below.
EDIT:
As per answer by Mathias R. Jessen, the equivalent to item #3 above is "dot sourcing". There is also an "intermediate" case (not identified above, perhaps there is also a way to get this in bash), where environment variables persist but PS variables don't.
My script:
# set_var.ps1
$env:TEST_VAR = 'test_var'
$TEST_VAR2 = 'test_var2'
What I checked:
> $env:TEST_VAR ; $TEST_VAR2 ;
> . .\set_var.ps1
> $env:TEST_VAR ; $TEST_VAR2 ;
test_var
test_var2
> Remove-Variable TEST_VAR2 ; Remove-Item env:TEST_VAR ;
> $env:TEST_VAR ; $TEST_VAR2 ;
> .\set_var.ps1
> $env:TEST_VAR ; $TEST_VAR2 ;
test_var
> Remove-Item env:TEST_VAR ;
> $env:TEST_VAR ; $TEST_VAR2 ;
> & .\set_var.ps1
> $env:TEST_VAR ; $TEST_VAR2 ;
test_var
(1) Example of persistent / non-persistent variables
I have script set_var.sh
with the following contents:
#!/bin/bash
export TEST_VAR=test_var
TEST_VAR2=test_var2
Then the following commands prove my point:
$ echo $TEST_VAR ; echo $TEST_VAR2
$ sh set_var.sh ; echo $TEST_VAR ; echo $TEST_VAR2
$ source set_var.sh ; echo $TEST_VAR ; echo $TEST_VAR2
test_var
test_var2
$ echo $TEST_VAR ; echo $TEST_VAR2
test_var
test_var2
$ env | grep TEST_VAR
TEST_VAR=test_var
$ unset TEST_VAR ; unset TEST_VAR2
$ echo $TEST_VAR ; echo $TEST_VAR2
$ ./set_var.sh ; echo $TEST_VAR ; echo $TEST_VAR2
$ echo $TEST_VAR ; echo $TEST_VAR2