2

I like to use (( )) when comparing integers in bash, but this doesn't seem possible with an exit code ($?) without assigning it to a variable first.

This works, but I have to assign status first:

some_command
status=$?
if (( status == 137 )); then
  foo
fi

This obviously doesn't work:

some_command
if (( ? == 137 )); then
  foo
fi

So I usually end up doing this:

some_command
if [[ $? -eq 137 ]]; then
  foo
fi
neu242
  • 15,796
  • 20
  • 79
  • 114
  • 3
    You can still use `$?` within `((...))`. It's possible to omit the `$`, but not mandatory. – Benjamin W. Aug 28 '23 at 14:20
  • 2
    Example: `false; if (( $? > 0 )); then echo err; fi` will output `err`. – Paul Hodges Aug 28 '23 at 14:21
  • 4
    Tangentially, testing exit codes is often an antipattern so you should consider if it's better to test the command directly (e.g. `if ! false ; then echo err ; fi`). If you care about the specific code and truly need to check it (137 vs other errors) then capturing in a variable might be less prone to bugs in case someone carelessly adds `echo I am testing things` after your command but before you check `$?`. Something like `my_cmd ; status=$?` on a single line makes those kinds of errors almost impossible. – tjm3772 Aug 28 '23 at 14:46
  • @BenjaminW. I don't think it is possible to omit the `$`. – Ed Morton Aug 28 '23 at 15:11
  • 1
    @EdMorton Yes, you're right, I meant "in general, in `((...))`, the `$` is optional", but not for quite a few special identifiers, including `$?`. – Benjamin W. Aug 28 '23 at 15:22
  • See [Why is testing "$?" to see if a command succeeded or not, an anti-pattern?](https://stackoverflow.com/q/36313216/4154375). – pjh Aug 28 '23 at 17:13
  • 1
    Also see [Bash Pitfalls #44 (cmd; (( ! $? )) || die)](https://mywiki.wooledge.org/BashPitfalls#cmd.3B_.28.28_.21_.24.3F_.29.29_.7C.7C_die). – pjh Aug 28 '23 at 17:13

1 Answers1

4

You can expand $? in the arithmetic expression:

some_command
if (( $? == 137 )); then
  foo
fi
Fravadona
  • 13,917
  • 1
  • 23
  • 35
  • 1
    Right but also - don't do that, do `some_command; ret=$?` all on 1 line then `if (( $ret == 137 )); then foo fi` below it [as @tjm3772 mentioned](https://stackoverflow.com/questions/76993623/in-bash-how-do-i-access-an-exit-code-within-double-parantheses?noredirect=1#comment135729888_76993623) – Ed Morton Aug 28 '23 at 15:24