Wanted to validate my understanding of why these situations behave differently:
I think #1 happens because the assignment and echo run as a single command in the shell and $SOME_VAR is not set when echo executes (shell expands all variables before execution).
#1
$ unset SOME_VAR
$ SOME_VAR=abcdef echo $SOME_VAR # prints nothing
I think #2 happens because the assignment and echo run as two separate commands in the same shell and $SOME_VAR is set in the shell when echo executes.
#2
$ unset SOME_VAR
$ SOME_VAR=abcdef ; echo $SOME_VAR
abcdef
I don't understand why #3 happens.
#3
$ unset SOME_VAR
$ SOME_VAR=abcdef ./test.sh # prints abcdef
abcdef
I think #4 happens because assignment and execution of shell script execute as two different commands in the parent shell and the child shell that executes commands in test.sh does not inherit SOME_VAR (since there is no export statement).
#4
$ unset SOME_VAR
$ SOME_VAR=abcdef ; ./test.sh # prints nothing
test.sh contains:
$ cat test.sh
#!/bin/bash
echo $SOME_VAR