Defining a shell script variable on the same line as sourcing another script
ksh, shell, unix
Solution
In the case of
MYVARIABLE="abc" . ~core/script.sh
`MYVARIABLE` is only set to `abc` for the duration of the source (`.`) command. So it will be in scope for the code in `~core/script.sh`.
In the case of
MYVARIABLE="abc"
. ~core/script.sh
it will be set both in the scope of the current shell/script and in the scope of `~core/script.sh`.
Try running the first, then `echo $MYVARIABLE` to see that it's still empty (assuming it started empty). Run the latter, `echo` again, and you'll see that its value is set in the current shell.
Edit:
Note that `MYVARIABLE` is visible in the scope of `~core/script.sh` in both cases here, but only because you are sourcing the script. If you were instead to run an executable (even an executable shell script), rather than source it, the behavior would be different.
MYVARIABLE=foo /usr/local/bin/some_executable
will have the variable in scope when executed, but
MYVARIABLE=foo
/usr/local/bin/some_executable
will not have the variable in scope. In order to have it propagate to an executable/subshell, you would have to `export` it:
MYVARIABLE=foo
export MYVARIABLE
/use/local/bin/some_executable
In Bourne-derived shells newer than ksh (bash, zsh), you can combine the assignment and export:
export MYVARIABLE=foo
but that doesn't work in ksh; you need two statements.
Problem
I am coming across lines in ksh scripts that declare a variable and source another shell script on the same line. For example: ``` MYVARIABLE="abc" . ~core/script.sh ``` Does this produce behaviour different from declaring them separately? For example: ``` MYVARIABLE="abc" . ~core/script.sh ```