3

I was surprised to find out that setting an environment variable modified the last exist code variable $?:

$ false
$ echo $?
1
$ false
$ FOO=BAR
$ echo $?
0
$ 

The bash manual says only this about $?:

($?) Expands to the exit status of the most recently executed foreground pipeline.

Where is the exit code of a variable being set documented? Can it fail?

  • FOO=$(BAR) it failed – Ipor Sircer Aug 16 '16 at 20:13
  • @IporSircer I tried that and you're right. It returned 127. However, is that the return code from "setting the variable" or from attempting to run a command that doesn't exist? – Steve Aug 16 '16 at 20:15
  • 1
    Also empty= a=${empty:?} – choroba Aug 16 '16 at 20:15
  • @Steve Yes that 127 is from the command not being found. I don't know where this was documented but this - the result of the command inside the substitution being transparently passed through variable assignment - is universal behavior that you can rely on, and any new shell that fails to implement this behavior while aiming to be Bourne-like/compatible is wrong. – mtraceur May 21 at 18:45
4

Assignment can fail if the right hand expression fails to evaluate

eg

$ x=HELLO
$ x=$((1/0))
bash: 1/0: division by 0 (error token is "0")
$ echo $?
1 

In this scenario the value of $x is left unchanged:

$ echo $x
HELLO
| improve this answer | |
  • 2
    Where is this documented? – Steve Aug 16 '16 at 20:30
  • Hmm, not sure where this is documented, but the return code from a variable assignment is the return code of the evaluation of the right hand side. That's why x=$(Nosuchcommand) returns an exit code of 127 because that's the standard "command not found" exit code. – Stephen Harris Aug 16 '16 at 20:36
  • man bash and search for EXIT STATUS. Is this the location that is being sought? – Timothy Martin Aug 16 '16 at 20:43
  • @TimothyMartin Not sure ... the man page talks about "commands" and "built-in commands", but that's where I'm confused. I never would have thought setting a variable was a "command" (although something like $(command) is obviously a command). – Steve Aug 17 '16 at 12:14
  • It's not entirely accurate, but I like to think of an assignment statement as a pre-command assignment that just happens to precede a null command that behaves like :. The assignments affect the current shell just like redirections on exec with no arguments affect the current shell. – chepner Aug 17 '16 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.