35

I am setting a variable like this:

myvar=$(command --params)

I want to check the exit code ($?) of my command afterwards. Checking $? like this always returns 0 because it successfully set the variable to the output of the command.

Is it possible to get the return value of command?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Questionmark
  • 3,885
  • 8
  • 37
  • 57
  • Related: http://unix.stackexchange.com/questions/340997/assignments-are-like-commands-with-an-exit-status-except-when-theres-command-su – Kusalananda Feb 22 '17 at 17:30
  • 6
    The premise here is wrong; `$?` [only returns 0 if the command succeeded.](http://unix.stackexchange.com/q/270828/135943) It's not simply "always 0 because of successful variable assignment." – Wildcard Feb 22 '17 at 17:47

1 Answers1

46

Yes, it is possible without even getting too far out of your way:

$ $(exit 3); echo $?
3

$ foo="$(echo bar; exit 3)"; echo $?; echo $foo
3
bar
DopeGhoti
  • 73,792
  • 8
  • 97
  • 133