I use Ubuntu 16.04 with the native Bash on it.
I'm not sure if executing
#!/bin/bash
myFunc() {
export myVar="myVal"
}
myFunc
equals in any sense, to just executing export myVar="myVal"
.
Of course, a global variable should usually be declared outside of a function (a matter of convention I assume, even if technically possible) but I do wonder about the more exotic cases where one writes some very general function and wants a variable inside it to still be available to everything, anywhere.
Would export
of a variable inside a function, be identical to exporting it globally, directly in the CLI, making it available to everything in the shell (all subshells, and functions inside them)?
export myvar
is called inside a ( subshell ), then the variable will still be unavailable in the parent scope. – Noam Manos Aug 23 '20 at 18:31export
in(set -x export MY_VAR=...)
– User Rebo Dec 22 '20 at 11:18set -x
will also be limited the subshell. – Kusalananda Dec 22 '20 at 12:09set -x
will prevent exporting variables in any scope. Didn't really refer to the subshell. – User Rebo Dec 22 '20 at 12:15set -x
will absolutely not prevent exporting variables! It turns on tracing in the shell (i.e. the shell will produce debug output). It's the subshell that prevents the variable from being visible outside of the subshell. – Kusalananda Dec 22 '20 at 12:18set -x
or added braces:export MYVAR=\first
set -x export MYVAR=\second
(export MYVAR=\third)
echo "MYVAR: $MYVAR"
– User Rebo Dec 22 '20 at 12:36;
(or a newline) betweenset -x
andexport
. They are two separate commands. What you wrote originally,set -x export var=value
would set$1
to the stringexport
, and$2
to the stringvariable=value
. I didn't spot the missing;
as it was such an odd command to give. – Kusalananda Dec 22 '20 at 12:44