15

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

Joel
  • 261
  • 2
  • 6
  • 7
    Shame on whoever downvoted your question, especially without leaving constructive feedback. It's a valid question, and the order in which bash does word/parameter/variable/tilde expansion and command execution is tricky. I'm giving you a +1. – Spiff Apr 30 '15 at 20:50
  • possible duplicate of [In bash, how can I define a “command scope” variable?](http://superuser.com/q/801822/150988) – see also [Is this a bash-specific method of calling a script: VARIABLE=value bash somescript?](http://superuser.com/q/791001/150988) – Scott - Слава Україні Apr 30 '15 at 22:36
  • technically, "echo 1" returns 0, and the output is 1... that is to say, "echo" exits with status "0", and displays to stdout the arguments. The phrasing "returns 1" to me was implying "exit staus", not "outputs", and was a bit confusing at first glance. – michael May 03 '15 at 07:45

3 Answers3

12

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.

Spiff
  • 101,729
  • 17
  • 175
  • 229
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:~# 
moonbutt74
  • 170
  • 1
  • 9
1

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

SOMETHING=1 eval 'echo $SOMETHING'

to prevent propagation of SOMETHING.

Daniel
  • 11
  • 1