Why does bash need && to echo a variable on one line?

Why does SOMETHING=1 && echo $SOMETHING need && to return 1
Why doesn't SOMETHING=1 echo $SOMETHING return 1


Solution 1:

Because bash does variable expansion before interpreting variable assignment statements. So, since SOMETHING was not previously defined, your command becomes…

SOMETHING=1 echo ''

…then gets executed.

Solution 2:

export and echo at the same time

root@kali:~# echo ${SOMETHING=1}
1
root@kali:~# echo $SOMETHING
1
root@kali:~# unset SOMETHING
root@kali:~# echo $SOMETHING

root@kali:~# echo ${SOMETHING=1}
1
root@kali:~# 

Another goofier example xD

root@kali:~# echo ${SOMETHING=1} ${PLUS=+} ${SUMTHIN=2} ${EQUALS==} && expr $SOMETHING $PLUS $SUMTHIN
1 + 2 =
3
root@kali:~# 

Solution 3:

You need to evaluate the variable later (after it gets assigned). Use, e.g.,

SOMETHING=1 eval 'echo $SOMETHING'

to prevent propagation of SOMETHING.