If I do this:
SUMAN_DEBUG=foo echo $SUMAN_DEBUG
I get no output
but if I do:
SUMAN_DEBUG=foo && echo $SUMAN_DEBUG
then I get
why is that?
[This answer is not correct. The problem is due to variable expansions occurring before variable assignments on the command line. See comments below. Also, this question was declared a duplicate and there is an excellent discussion in the original question. -gt]
SUMAN_DEBUG=foo is a local environment variable assignment for a local variable that exists only for the command it prefaces. In your second case, there is no command because the
&& initiates a list of command where in your case, the first command is null (so the environment variable has no command to affect) and the second is executed but has no environment variable set for it.
You could add
export to the assignment so that the variable would become a global environment variable. But then it would persist after the list of commands is complete.
Another option is to put the entire command list in parenthesis to execute it in a subshell:
(export SUMAN_DEBUG=foo && echo $SUMAN_DEBUG)
In this case, the persistent environment variable would be set in a subshell and that environment would disappear when the subshell completed its work).
In command line you need to separate commands using either
&&. Space it is just not a delimiter for CLI commands.
&& the second command will be executed if the first command exits successfully (exit code 0).
; the second command will be executed no matter what is the exit status of first command.
# a1;echo hello bash: a1: command not found hello # a1 && echo hello bash: a1: command not found
In scripts the first command and the second command is separated by a new line
\n character, also recognized by bash.