13

In the Bash shell, I can get the command exit status through the $? variable:

# ps -ef | grep "haha"
root     15439 15345  0 23:02 pts/0    00:00:00 grep --color=auto haha
# echo $?
0

Is it available only in the Bash shell? Or can I also use it in other shells?

psmears
  • 461
  • 3
  • 8
Nan Xiao
  • 1,387
  • 6
  • 18
  • 33
  • 8
    You can use it in any POSIX shell, it's one of [special parameters](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_05_02) – cuonglm Jan 18 '16 at 02:08
  • Related: [Default exit code when process is terminated?](http://unix.stackexchange.com/a/99134) – Stéphane Chazelas Jan 18 '16 at 11:17

2 Answers2

20

The $? exit-code is common to any shell that follows POSIX, and is described in 2.5.2 Special Parameters:

?
Expands to the decimal exit status of the most recent pipeline (see Pipelines).

Thomas Dickey
  • 75,040
  • 9
  • 171
  • 268
  • 5
    Not only POSIX shell, all Bourne-like shells including the Bourne shell (which I believe was the one introducing it, the Mashey shell had it as `$r` I believe). So that's the sh of virtually all Unix-like systems since Unix V7 in the late 70s, Most other shells (csh, tcsh, fish, rc) have it as `$status`. – Stéphane Chazelas Jan 18 '16 at 11:33
  • 2
    And many scripting languages: Perl, Ruby, etc. – OrangeDog Jan 18 '16 at 13:52
14

As Thomas Dickey said, any POSIX shell (ie. pretty much all of them) will have $?.

This question interested me quite a bit, so I tested it on any shell I could get my hands on:

  • mksh
  • zsh
  • /bin/sh on my Samsung Galaxy S5
  • /bin/sh on my router
  • tcsh
  • ksh
  • dash
  • /bin/sh on my virtual UNIX System V from 1989 or so
  • cmd.exe and powershell.exe on my Windows 10 computer

and $? worked in all of these but fish and cmd.exe.

Found two interesting things:

1. $? works in Windows PowerShell!

Well, to a point. Instead of returning 0 or a higher number, it's just True and False.

PS C:\WINDOWS\system32> echo $?
True
PS C:\WINDOWS\system32> gfdhgfhfdgfdg
gfdhgfhfdgfdg : The term 'gfdhgfhfdgfdg' is not recognized as the name of a cmdlet, ...(big long error output).....
PS C:\WINDOWS\system32> echo $?
False

2. $? doesn't work in the shell fish.

However, when you type $? in fish, you get this message:

~$ echo $?
$? is not the exit status. In fish, please use $status.
fish: echo $?

I haven't used it much but I'm not surprised, fish seems to have its own interesting shell language, completely different from bash or whatever.

apricot boy
  • 1,153
  • 7
  • 11
  • Most shells (fish, csh, tcsh, rc, zsh) use `$status` which is a lot more straightforward/legible IMO. Only Bourne-like shells (among Unix shells) use `$?` AFAIK. – Stéphane Chazelas Jan 18 '16 at 11:35
  • 3
    Just depends on how you are reading. I read mentally `$?` as "sh## happened?" and after that, i never forgot the meaning of this special variable :) –  Jan 18 '16 at 12:58