'Is it possible to pass variables from a BASH Script into PWSH on Linux
We have a project where we want to run some Bash & Powershell scripts on Linux. We will be using a BASH Script to run some processes with various variables, execute a powershell script & then complete some more BASH commands.
If we have variables set in the bash script and then we execute the powershell script in the same BASH session, is there a way to pass those variables across to Powershell?
Solution 1:[1]
You can pass values via environment variables, which Bash (and POSIX-compatible shells in general) makes easy:
$ foo='BAR'; bar='BAZ' # define sample Bash shell vars.
$ foo="$foo" bar="$bar" pwsh -noprofile -command '$env:foo; $env:bar'
BAR
BAZ
Note how prepending foo="$foo" and bar="$bar" defined shell variables $foo and $bar as process-scoped environment variables for the pwsh call.
That is, these environment variables are only in effect for the pwsh child process.
Alternatives:
You can define environment variables separately, beforehand - e.g.,
export foo='BAR', but note that these stay in effect for the lifetime of the current process that thebashscript runs in (unless you undefine them later).To make all variables in your
bashscript environment variables automatically (again for the lifetime of the current process), you can place aset -astatement before you create your regular shell variables. Then a regular assignment such asfoo='BAR'automatically createsfooas an environment variable that PowerShell can access as$env:foo.
Solution 2:[2]
If you export a bash variable it will be available in powershell as $env:variablename:
example=/var/data
export example
pwsh -noprofile -command '$env:example;'
returns /var/data
In Powershell you can run Get-ChildItem Env: to list all environment variables.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Mike A |
